2012-06-05 37 views
1

我想查找數組中第二高的變量。查找數組中第二高的變量

例如,如果我有:

$cookies = array(
       "chocolate" => "20", 
       "vanilla" => "14", 
       "strawberry" => "18", 
       "raspberry" => "19", 
       "bluebery" => "29" 
); 

我可以使用max($cookies)找到最高的變量,這是"bluebery" => "29"

但是,如何找到第二高?"chocolate" => "20"

+2

選項一:從陣列中刪除最大元素並再次查找最大值。第二:排列數組並取第二個元素。 – Leri

+0

你嘗試過什麼方法?想到一對夫婦的想法:你可以穿過陣列並選出最高的兩個,類似於選擇較高的一個。另一個是你可以挑選第二個。 – GreenMatt

回答

14

排序,並得到第二項是最簡單的方法:

arsort($cookies); 
$keys = array_keys($cookies); 

echo $keys[1]; // chocolate 
echo $cookies[$keys[1]]; // 20 

如果你想要一個更有效的方法,你也可以做手工,通過保持雙方最高和第二高的項目的跟蹤在同一時間:

function secondMax($arr) { 
    $max = $second = 0; 
    $maxKey = $secondKey = null; 

    foreach($arr as $key => $value) { 
     if($value > $max) { 
      $second = $max; 
      $secondKey = $maxKey; 
      $max = $value; 
      $maxKey = $key; 
     } elseif($value > $second) { 
      $second = $value; 
      $secondKey = $key; 
     } 
    } 

    return array($secondKey, $second); 
} 

用法:

$second = secondMax($cookies); 
echo "{$second[0]} => {$second[1]}"; // chocolate => 20 
+0

你的功能也很棒!!!!!謝謝! – supercoolville

+0

好的解決方案,但我懷疑循環自己比本地編譯函數更有效嗎? –

+0

$ secondMax未定義函數 –

5

爲了好玩,你可以使用兩次max() :)

例如:

  • 複製數組
  • 運行max()
  • 再次取出最大
  • 運行max()

另一種方法是根據值對數組進行排序並獲取數組的第二個元素。我會很好奇更快。可能是那種。

0

排序陣列降,並採取第第二個價值。或者,爲了保存,取第一個值並遍歷數組,直到找到一個較小的值。

1

嘗試:

asort($cookies); 
end($cookies); 
prev($cookies); 
list($key,$value) = each($cookies); 

或扭轉它

arsort($cookies); 
reset($cookies); 
next($cookies); 
list($key,$value) = each($cookies); 

** 編輯 **

我想我反正分享這個,如果有人碰到這個跌跌需要它:

/** 
* Returns the key => value pair with the specific rank. 
* if $rank is 0, falase is returned. If $rank is positive, 
* then the $rank th smallest pair is returned. If $rank 
* is negative, then the $rank th biggest pair is returned. 
* If $rank range is outside the size of the array, false 
* is returned. If a callable function is provided, it will 
* be used to sort the data. If $keySort is true, then the 
* data will be sorted by keys instead (the callback functions 
* will receive the keys to compare instead of values) 
* 
* @param $data array 
* @param $rank int 
* @param $cmd_function callable (optional) 
* @param $keySort boolean (optional) 
* @return array   the key => value pair or false 
*/ 
function findByRank($data, $rank, $cmd_function = null, $keySort = false) { 
    if (($rank == 0) || (abs($rank) > count($data))) { 
     return false; 
    } 
    $sort = ($keySort?'k':'a').'sort'; 
    if ($cmd_function != null) { 
     $sort = 'u'.$sort; 
     $sort($data, $cmd_function); 
    } else { 
     $sort($data); 
    } 

    if ($rank > 0) { 
     reset($data); 
     $next = 'next'; 
    } else { 
     end($data); 
     $next = 'prev'; 
     $rank = abs($rank); 
    } 
    while (--$rank > 0) $next($data); 
    return each($data); 
} 




$cookies = array(
       "chocolate" => "20", 
       "vanilla" => "14", 
       "strawberry" => "18", 
       "raspberry" => "19", 
       "bluebery" => "29" 
); 

header('Content-type:text/plain; charset=utf-8'); 
var_dump(findByRank($cookies, -10)); // -> false 
var_dump(findByRank($cookies, -2)); // -> 'chocolate' key=>value pair 
var_dump(findByRank($cookies, -1)); // -> 'blueberry' key=>value pair 
var_dump(findByRank($cookies, 0)); // -> false 
var_dump(findByRank($cookies, 1)); // -> 'vanilla' key=>value pair 
var_dump(findByRank($cookies, 3)); // -> 'raspberry' key=>value pair 
+0

'ksort'按鍵排序。你的意思是'asort'嗎? – Ryan

+0

哎呀,是的,我在想「排序保存鍵聯合」,但'asort'是正確的功能,是的 –

1
rsort($cookies); 
echo $cookies[1]; 
+1

你不能拿到鑰匙。 –

2
arsort($cookies) AND array_shift($cookies) AND list($k, $v) = each($cookies); 
echo "$k => $v"; // chocolate => 20 
+0

非常感謝!!!!!!!!!! – supercoolville

0

檢查該URL

http://maheshbokkisam.blogspot.in/2013/04/find-nth-highest-value-in-array-without.html

查找給定陣列第N/N個最高值,而無需使用任何排序在PHP

$ar = array(23,56,87,12,98,85,24,54,99,100,1,4,5,2,76,37,92); 

$n = count($ar) - 5; 

for($i = 0; $i < $n; $i++){ 
    // Get the max value from array // get the Nth value from last loop 
    echo $a = max($ar); 

    echo "<br /><pre>"; print_r($ar); 

    $ar = array_flip($ar); // Flip the array 
    //print_r($ar); 

    unset($ar[$a]);   // Unset the max value from array 
    //print_r($ar); 

    $ar = array_flip($ar); // Flip the array 
    echo "</pre>"; 
    echo "<hr />"; 
} 

0
function second_largest($arr) 
{ 
    sort($arr, SORT_NUMERIC); 

    return($arr[count($arr) - 2]); 
} 

//echo 3 

echo second_largest(array(0, 3, 4, 1, 2)); 
0
<?php 

// Finding Second highest number (In case of index of array is random) 
$arr = [-5 => 33, -4 => -2, 8 => 0, 44, 44, 44, 44, 44]; 
$max = -INF; 
$secondMax = -INF; 
$size = sizeof($arr); 
if ($size > 1) { 
    foreach ($arr as $key => $value) { 
     echo "KEY-> ", $key, "VALUE->", $value, "\n"; 
     if ($value > $max) { 
      $max = $value; 
     } else { 
      if ($value < $max && $value > $secondMax) { 
       $secondMax = $value; 
      } 
     } 
    } 
} else if ($size == 0) { 
    $max = "No Max element"; 
    $secondMax = "No Second highest element"; 
} else { 
    foreach ($arr as $key => $value) { 
     $max = $arr[$key]; 
     $secondMax = "No second highest element"; 
    } 
} 

echo "maxvalue = ", $max, "\n"; 
echo "secondmax =", $secondMax; 
相關問題