聚合并计算数组

时间:2013-12-17 13:34:30

标签: php arrays

我有一个数组,我想聚合其中的每个单词并计算它们,如下:

 Array
    (
        [0] => Notice
        [1] => co
        [2] => co
        [3] => Notice
        [4] => co
        [5] => co
        [6] => sls
    ) 

应如下所示:

Array
(
    [Notice] => 2
    [co] => 4
    [sls] => 1
)

这样做的方法是什么?

感谢

2 个答案:

答案 0 :(得分:4)

您需要查看array_count_values()

<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>

输出:

Array
(
    [1] => 2
    [hello] => 2
    [world] => 1
)

答案 1 :(得分:2)

试试这样:

<?php
$array = array("Notice", "co", "co", "Notice", "co", "co", "sls");
print_r(array_count_values($array));
?>

输出

Array
(
    [Notice] => 2
    [co] => 4
    [sls] => 1
)

了解更多信息:http://www.php.net/manual/en/function.array-count-values.php