東西:Get the element with the highest occurrence in an arrayPHP獲取用5最高發生元件在陣列中與此類似
差異是我需要多於1個結果,需要5個結果完全。所以在(大)數組中出現5個最高的出現。
謝謝!
東西:Get the element with the highest occurrence in an arrayPHP獲取用5最高發生元件在陣列中與此類似
差異是我需要多於1個結果,需要5個結果完全。所以在(大)數組中出現5個最高的出現。
謝謝!
PHP實際上提供了一些方便array functions你可以用它來實現這一目標。
實施例:
<?php
$arr = array(
'apple', 'apple', 'apple', 'apple', 'apple', 'apple',
'orange', 'orange', 'orange',
'banana', 'banana', 'banana', 'banana', 'banana',
'pear', 'pear', 'pear', 'pear', 'pear', 'pear', 'pear',
'grape', 'grape', 'grape', 'grape',
'melon', 'melon',
'etc'
);
$reduce = array_count_values($arr);
arsort($reduce);
var_dump(array_slice($reduce, 0, 5));
// Output:
array(5) {
["pear"]=> int(7)
["apple"]=> int(6)
["banana"]=> int(5)
["grape"]=> int(4)
["orange"]=> int(3)
}
EDIT:添加array_slice,如下面阿利克斯的交使用。
構建計數的數組,並把它們以相反的順序:
$mode = array_count_values($input);
arsort($mode);
$i = 0;
foreach ($mode as $k => $v) {
$i++;
echo "$i. $k occurred $v times\n";
if ($i == 5) {
break;
}
}
在這裏你去:
$yourArray = array(1, "hello", 1, "world", "hello", "world", "world");
$count = array_count_values($yourArray);
arsort($count);
$highest5 = array_slice($count, 0, 5);
echo '<pre>';
print_r($highest5);
echo '</pre>';
+1'array_slice' – Matt 2010-02-01 13:04:12
@Matt:謝謝,當我發佈我的答案時,我沒有意識到你已經在使用'array_count_values()'函數。 – 2010-02-01 13:12:04
你的徽章數量是太酷了...... 12,2^7 - 1,2^8 + 1! – 2010-02-01 13:26:41