【发布时间】:2010-02-01 12:40:01
【问题描述】:
类似的东西:Get the element with the highest occurrence in an array
不同之处在于我需要超过 1 个结果,总共需要 5 个结果。所以(大)数组中出现次数最多的 5 个。
谢谢!
【问题讨论】:
类似的东西:Get the element with the highest occurrence in an array
不同之处在于我需要超过 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)
}
编辑:添加了 array_slice,如下面的 Alix 帖子中使用的那样。
【讨论】:
给你:
$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>';
【讨论】:
array_count_values() 函数。
构建计数数组并将它们倒序排列:
$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;
}
}
【讨论】: