数组group by and count php [duplicate]

fnvucqvd  于 2023-04-19  发布在  PHP
关注(0)|答案(2)|浏览(85)

此问题已在此处有答案

Get count of each unique value in one column of a 2d array(2个答案)
6个月前关闭。
我有2个日志文件,我读取并获得数组的内容。我得到的数组是这样的:

2 => array:9 [▼
"app" => "a.log"
"context" => "local"
"level" => "error"
"level_class" => "danger"
"level_img" => "exclamation-triangle"
"date" => "2018-10-25 21:01:04"
"text" => "Class 'Arcanedev\Support\Collection' not found 
]
3 => array:9 [▼
"app" => "b.log"
"context" => "local"
"level" => "error"
"level_class" => "danger"
"level_img" => "exclamation-triangle"
"date" => "2018-10-26 16:49:07"

我需要获得每个文件的所有错误级别的计数。例如:

a.log => "count of error level for a.log",
b.log => "count of error levels for b.log"

我试过:

foreach($names as $filename){
            $logs = $this->getLogs($this->filepath.$filename);                
            $result = array();
            $result[ $filename ] = $logs;                
            foreach($logs as $log){
                //$result[ $log['level'] ][] = $log;
                $result[ $filename ][] = $log;
                $counts = array_map('count', $result);
            }
        }

这给了我这个结果:

array:1 [▼
   "a.log" => 20
]

任何帮助都很感激。提前谢谢你。:)

u3r8eeie

u3r8eeie1#

我自己解决了这个问题。我尝试了另一种方法,它似乎有效。下面是解决方案:

foreach($names as $filename){
   $logs = $this->getLogs($this->filepath.$filename);                
   $result = array();                
   foreach($logs as $log){                    
      $result[ $log['app'] ][] = $log;
      $counts = array_map('count', $result);
   }
}

结果是:

array:2 [▼
  "b-laravel.log" => 3
  "laravel.log" => 7
 ]

谢谢你。

m2xkgtsf

m2xkgtsf2#

就像

print_r(array_count_values(array_column($array, 'app')));

我想测试一下,但是你没有提供一个我可以使用的数组。理论上它应该工作。

相关问题