如何从集合中查找最常出现的值?

时间:2016-02-02 12:02:55

标签: php sorting laravel collections

嗨我有一个数字集合,我想找到最多的数字,然后发现第二个最多,然后是第三个发生到10,并将结果存储在一个数组中。 该集合看起来像这样

Illuminate\Database\Eloquent\Collection Object
(
    [items:protected] => Array
        (
            [0] => 12
            [1] => 194
            [2] => 241
            [3] => 4
            [4] => 29
            [5] => 4
            [6] => 12
            [7] => 15
            [8] => 21
            [9] => 31
            [10] => 281
            [11] => 4
            [12] => 6
            [13] => 4
            [14] => 2
            [15] => 6
            [16] => 4
            [17] => 4
            [18] => 4
            [19] => 15
            [20] => 4
            [21] => 4
            [22] => 13
            [23] => 10
            [24] => 8
            [25] => 8
            [26] => 2
            [27] => 2
            [28] => 2
            [29] => 17
            [30] => 4
            [31] => 20
            [32] => 2
            [33] => 4
            [34] => 20
            [35] => 6
        )

)

所以我想找到最常出现的一个,直到第10个最常出现的数字。

1 个答案:

答案 0 :(得分:3)

使用array_count_values,这是您的参考链接http://www.w3schools.com/php/func_array_count_values.asp

<?php
$a=array("A","Cat","Dog","A","Dog");
print_r(array_count_values($a));
?>

输出

Array ( [A] => 2 [Cat] => 1 [Dog] => 2 )