我有这个数组:
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)
,但它不起作用。
任何想法如何解决这个问题?
答案 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));