数组分组并计数php

时间:2018-10-26 23:50:03

标签: php arrays laravel-5 logging

我有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
]

感谢您的帮助。 先感谢您。 :)

2 个答案:

答案 0 :(得分:0)

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

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
 ]

谢谢。

答案 1 :(得分:0)

类似

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

我会测试它,但是您没有提供我可以使用的数组。从理论上讲,它应该起作用。