phparraysmultidimensional-arrayconcatenationgrouping

Group rows of a 2d array by a column and consolidate another column as comma-separated values within each group


I have php array

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
        )

)

I want to check merge array key tree_id
like all tree_id == 2 then its come out with array("tree_id"=>2,"node"=>2620,4,2619);
if tree_id == 1 then its come out with array("tree_id"=>1,"node"=>5746,5952)


Solution

  • Try this:

    $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 will have the elements as you wished and this array will be indexed by tree_id