2010-06-05 85 views
1

我有這樣如何找到重複的和最高值在數組

array={'a'=>'2','b'=>'5', 'c'=>'6', 'd'=>'6', 'e'=>'2'}; 

的數組值數組可能取決於$ _ POST變量是不同的。我的問題是如何找到我的數組中的最高值並返回索引鍵。在我的情況下,我需要得到'c'和'd',值爲6.不知道如何做到這一點。任何幫助將不勝感激。謝謝。

回答

4
$max = max(array_values($array)); 
$keys = array_keys($array, $max); 
+0

感謝您的回覆。 +1 – FlyingCat 2010-06-05 13:39:32

+3

你不應該使用'max(array_values($ array))'嵌入。 OP只想獲得價值。將它分成兩個語句。 '$ keys'將只包含這些鍵。 – 2010-06-05 13:39:35

+0

@Felix Kling - 我沒有想到他並不關心最大數量...... – mmattax 2010-06-05 13:42:14

0

或者這應該做的魔力,它可能會比PHP快的內置功能

$maxValue = -1; 
$max = array(); 
foreach ($items as $key => $item) { 
    if ($item == $maxValue) { 
     $max[] = $key; 
    } elseif ($item > $maxValue) { 
     $max = array(); 
     $max[] = $key; 
     $maxValue = $item; 
    } 
} 
+1

請你解釋爲什麼這可能更快? – 2010-06-05 13:36:33

+0

最大值,array_keys和array_values最可能都是遍歷數組,我的函數只是一次。然而,無論如何,這是如此之快無關緊要。 – 2010-06-05 14:15:40

1

看一看arsort將逆向排序數組,並保持索引關係。所以:

arsort($array); 

這將以數組頂部的最大值結束。取決於你需要的array_unique可以從你的數組中刪除重複的值。

+0

我需要獲取重複值的索引。但thx雖然。 +1 – FlyingCat 2010-06-05 13:38:42

+1

排序爲O(n log n)。這可以在O(n)中完成。 – 2010-06-05 13:40:10

1
$array = array(
    'key1' => 22, 
    'key2' => 17, 
    'key3' => 19, 
    'key4' => 21, 
    'key5' => 24, 
    'key6' => 8, 
); 

function getHighest($array) 
{ 
    $highest = 0; 
    foreach($array as $index => $value) 
    { 
     if(is_numeric($value) && $value > $highest) 
     { 
      $highest = $index; 
     } 
    } 
    return $highest; 
} 

echo getHighest($array); //key5 
+0

我需要得到重複的密鑰索引。雖然功能很好。 +1 – FlyingCat 2010-06-05 13:40:55

+0

更改爲返回索引鍵。 – RobertPitt 2010-06-05 13:41:31

相關問題