如何计算数组中键出现次数的值


how to calculate number of values of key occurance in an array

我有一个类似的数组

Array
(
 [0] => Array
    (
        [label] => A
        [uid] => 429
        [country_id] => 3
        [date] => 2015-02-11 13:55:34
        [DiffDate] => 20
    )
[1] => Array
    (
        [label] => A
        [uid] => 429
        [country_id] => 2
        [date] => 2015-02-11 13:55:34
        [DiffDate] => 20
    )
  ...... and so on
)

现在我必须计算国家记录的出现次数,例如

country 1 has total 10 occurrence 
country 2 has total 20 occurrence

我需要帮助,因为有很多阵列创建,我也得到了不同阵列的国家id

提前感谢

有很多方法可以解决这个问题。我喜欢以下方法:

  1. 重新构造阵列,因此它只是使用array_column 的国家列表

    $countries = array_column($array, 'country_id');
    

或适用于PHP 5.4

    $countries = array_map(function($item) {
        return $item['country_id'];
    }, $array);
  1. 使用array_count_values获取每个国家的出现次数

    $occurrences = array_count_values($countries);
    

根据条件添加国家/地区(备选步骤1)

如果您需要在将国家/地区添加到$countries数组之前进行检查,那么使用foreach循环比使用array_map要好。

$countries = []
foreach ($array as $item) {
    if ($item['DiffDate'] >= 3) $countries[] = $item['country_id'];
}