我有 php 数组
Array
(
[0] => stdClass Object
(
[id] => 9956
[event_url_node_id] => 2722
[tree_id] => 2
[node] => 2620
)
[1] => stdClass Object
(
[id] => 9957
[event_url_node_id] => 2722
[tree_id] => 2
[node] => 4
)
[2] => stdClass Object
(
[id] => 9958
[event_url_node_id] => 2722
[tree_id] => 2
[node] => 2619
)
[3] => stdClass Object
(
[id] => 9959
[event_url_node_id] => 2722
[tree_id] => 1
[node] => 5746
)
[4] => stdClass Object
(
[id] => 9960
[event_url_node_id] => 2722
[tree_id] => 1
[node] => 5952
)
)
我想检查合并数组键
tree_id
array("tree_id"=>2,"node"=>2620,4,2619);
array("tree_id"=>1,"node"=>5746,5952)
试试这个:
$finalArray = array();
foreach($array as $val) {
if(array_key_exists($val->tree_id, $finalArray)) {
$finalArray[$val->tree_id]['node'] .= ','.$val->node;
} else {
$finalArray[$val->tree_id]['node'] = $val->node;
}
$finalArray[$val->tree_id]['tree_id'] = $val->tree_id;
}
$finalArray
将具有您想要的元素,并且该数组将由 tree_id 索引