PHP计算数组中的单词

时间:2016-09-22 13:59:21

标签: php arrays counting

好的,所以在我的情况下,我有一个像这样的阵列(但更大)

$array = [
    0 => "TOD",
    1 => "TOD",
    2 => "MAX",
    3 => "JEFF",
    4 => "TOD",
    5 => "MAX",
    6 => "JEFF",
    7 => "MAX",
    8 => "MAX"
];

现在我的问题是,有没有办法计算TODJEFF&的出现次数?数组MAX中有$array,然后将它们存储到单独的变量中,因此,例如,期望的结果是有3个单独的变量,这些变量带有值(基于显示的示例代码)以上)

$todAmount = 3;
$jeffAmount = 2;
$maxAmount = 4;

我做了很多研究,并没有真正找到一个好方法来做到这一点:/
感谢阅读!

2 个答案:

答案 0 :(得分:1)

array_count_values()可能就是你所需要的。

<?php

$array = [
    0 => "TOD",
    1 => "TOD",
    2 => "MAX",
    3 => "JEFF",
    4 => "TOD",
    5 => "MAX",
    6 => "JEF",
    7 => "MAX",
    8 => "MAX"
];
    print_r(array_count_values($array));
?>

答案 1 :(得分:0)

那应该对你有帮助......

http://php.net/manual/en/function.array-count-values.php

print_r(array_count_values($array));