doudi2431 2015-03-03 06:34
浏览 31

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

I have an array like this

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
)

Now I have to calculate number of occurrences of country records example

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

I need help as there are lot of arrays created also I am getting country id as different array

thanks in advance

  • 写回答

1条回答 默认 最新

  • douqiu0796 2015-03-03 06:47
    关注

    There are a number of ways to tackle this. I like the following approach:

    1. Restructure the array, so it's just a list of countries using array_column

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

    or for PHP 5.4

        $countries = array_map(function($item) {
            return $item['country_id'];
        }, $array);
    
    1. Use array_count_values to get the number of occurrences for each country

      $occurrences = array_count_values($countries);
      

    Adding a country on a condition (alternative step 1)

    If you need to do a check before adding the country to the $countries array, you're better of with a foreach loop than with array_map.

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

报告相同问题?

悬赏问题

  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64
  • ¥15 iOS 自定义输入法-第三方输入法
  • ¥15 很想要一个很好的答案或提示
  • ¥15 扫描项目中发现AndroidOS.Agent、Android/SmsThief.LI!tr
  • ¥15 怀疑手机被监控,请问怎么解决和防止
  • ¥15 Qt下使用tcp获取数据的详细操作
  • ¥15 idea右下角设置编码是灰色的
  • ¥15 全志H618ROM新增分区
  • ¥15 在grasshopper里DrawViewportWires更改预览后,禁用电池仍然显示