带有多维数组的PHP array_count_values

时间:2015-09-16 08:41:24

标签: php arrays

我有这个数组:

Array ( 
    [0] => stdClass Object ( [id] => 123 [name] => Alex ) 
    [1] => stdClass Object ( [id] => 124 [name] => John ) 
    [2] => stdClass Object ( [id] => 123 [name] => Alex ) 
    [3] => stdClass Object ( [id] => 124 [name] => John) 
    [4] => stdClass Object ( [id] => 126 [name] => Paul )
 )

我希望输出如下:

 Array ( 
    [0] => Array ( [id] => 123 [name] => Alex [count] = 2 ) 
    [1] => Array ( [id] => 124 [name] => John [count] = 2 ) 
    [2] => Array ( [id] => 126 [name] => Paul [count] = 1 )
  )

我尝试使用array_count_values($array),但它不起作用。

任何想法如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

您可以简单地使用Class和简单的array_map一样使用

foreach

<强>输出:

foreach(array_map("get_object_vars",$arr) as $val){
    $hash = $val['id'];
    if(isset($result[$hash])){
        $result[$hash]['count'] += $result[$hash]['count'];
    }else{
        $result[$hash] = $val;
        $result[$hash]['count'] = 1;
    }
}
print_r(array_values($result));