计算特定值在数组中出现的频率

时间:2010-03-13 00:08:11

标签: php arrays count

我知道php的函数count(), 但是计算一个值出现在数组中的频率有什么作用呢?

示例:

$array = array(
  [0] => 'Test',
  [1] => 'Tutorial',
  [2] => 'Video',
  [3] => 'Test',
  [4] => 'Test'
);

现在我想计算“测试”出现的频率。

2 个答案:

答案 0 :(得分:14)

PHP有一个名为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)

尝试使用array_count_values功能,您可以在此处的文档中找到有关该功能的更多信息:http://www.php.net/manual/en/function.array-count-values.php

该页面的示例:

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

将产生:

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