我發現this thread關於根據已知值從數組中選取最接近/最接近的值。如果你想從一個數組中看到相同的話,選擇兩個最接近的值?PHP:從數組中獲取兩個最近的鄰居?
$rebates = array(
1 => 0,
3 => 10,
5 => 25,
10 => 35)
我發現this thread關於根據已知值從數組中選取最接近/最接近的值。如果你想從一個數組中看到相同的話,選擇兩個最接近的值?PHP:從數組中獲取兩個最近的鄰居?
$rebates = array(
1 => 0,
3 => 10,
5 => 25,
10 => 35)
$rebates = array(
1 => 0,
3 => 10,
5 => 25,
10 => 35);
function getArrayNeighborsByKey($array, $findKey) {
if (! array_key_exists($array, $findKey)) {
return FALSE;
}
$select = $prevous = $next = NULL;
foreach($array as $key => $value) {
$thisValue = array($key => $value);
if ($key === $findKey) {
$select = $thisValue;
continue;
}
if ($select !== NULL) {
$next = $thisValue;
break;
}
$previous = $thisValue;
}
return array(
'prev' => $previous,
'current' => $select,
'next' => $next
);
}
通過 「兩個最近的」 你的意思是兩個小於或等於$物品價值?
總之,從這個問題的答案其他線程,這是
$percent = $rebates[max(array_intersect(array_keys($rebates),range(0,$items)))];
開始你可以去
$two_nearest = array_slice(array_intersect(array_keys($rebates),range(0,$items)), -2);
$most_near = $rebates[$two_nearest[1]];
$less_near = $rebates[$two_nearest[0]];
這或許可以減少使用array_map
的一行代碼,但我認爲它已經過了。
$rebates = array(
1 => 0,
3 => 10,
5 => 25,
10 => 35)
$distances = array();
foreach($rebates as $key=>$item) {
if ($key == 5) continue;
$distances = abs($rebates[5] - $item);
}
sort($distances, SORT_NUMERIC)
現在你有一個數組中的所有項目,它們的距離爲$ rebates [5]排序。所以你可以得到最接近的兩個。 或三個最接近的。隨你。
請記住,2個項目可以有相同的距離。
條件需要包裝在括號`(`&`)`中。 – alex 2010-11-25 23:47:08