按列对二维数组的行进行分组,并将另一列合并为每组内以逗号分隔的值

问题描述 投票:0回答:1

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

像所有的 tree_id == 2 一样,它的结果是
array("tree_id"=>2,"node"=>2620,4,2619);

如果tree_id == 1 那么它的结果是
array("tree_id"=>1,"node"=>5746,5952)

php arrays multidimensional-array concatenation grouping
1个回答
1
投票

试试这个:

$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 索引

© www.soinside.com 2019 - 2024. All rights reserved.