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

时间:2015-03-03 06:34:51

标签: php arrays

我有一个像这样的数组

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 个答案:

答案 0 :(得分:3)

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

  1. 重组数组,因此它只是使用array_column

    的国家/地区列表
    $countries = array_column($array, 'country_id');
    
  2. 或PHP 5.4

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

      $occurrences = array_count_values($countries);
      

    2. 根据条件添加国家/地区(替代步骤1)

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

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