Nested array to flat with parent_id creating

629 Views Asked by At

I want to create flat array from nested array, like this one:

[0]=>Array(
  "id"=>1,
  "positions">Array(
    [0]=>Array(
      "id"=>2
      ),
    [1]=>Array(
      "id"=>3
      "positions"=>Array(
         [0]=>Array(
         "id"=>4
         )
      )
   )

to something like this:

[0]=>Array(
  "id"=>1,
  "parent_id"=>0
  ),
[1]=>Array(
  "id"=>2,
  "parent_id"=>1
  ),
[2]=>Array(
  "id"=>3,
  "parent_id"=>1
  ),
[3]=>Array(
  "id"=>4,
  "parent_id"=>3
  )

I don't have parent_id in nested structure, so all the trick is to "ride" trough the nested array, and add 'parent_id', base on id from parent node. I know how to flat the array, but I need parent_id information.

2

There are 2 best solutions below

0
On

Use this code

$result =   array();
function generateArray($array,$parent=0){
    foreach ($array as $key=>$val){
        $tmp = array();
        if(!empty($val['id'])){
            $tmp['id'] = $val['id'];
            $tmp['parent_id'] = $parent;
            $result[] = $tmp;
        }
        if(!empty($val['positions'])){
            $result=array_merge($result,generateArray($val['positions'],$val['id']));
        }
    }
    return $result;
}

Your array must be of this structure

$data   =   array(0=>array("id"=>1,"positions"=>array(0=>array("id"=>2),1=>array("id"=>3,"positions"=>array(0=>array("id"=>4))))));

Then call the function generateArray(),

var_dump(generateArray($data));
0
On

Try below code : i hope useful it...

<?php

$array = array(array(
  "id"=>1,
  "positions" => 
    array(
       array(
         "id"=>2
       ),
       array(
          "id"=>3,
          "positions"=>
               array(
                  array(
                    "id"=>4
                  )
                )
        )
    )
  ));

echo "<pre>";
print_r(getArray($array));
echo "</pre>";
exit;


function getArray($array,$parent_id = 0)
{
    $result = array();
    foreach ($array as $value)
    {
        $tmp = array();
        $tmp['id'] = $value['id'];
        $tmp['parent_id'] = $parent_id;         
        $result[] = $tmp;
        if(!empty($value['positions']))
        {
            $result= array_merge($result,getArray($value['positions'],$value['id']));
        }

    }

    return $result;


}

?>

OUTPUT :

Array
(
    [0] => Array
        (
            [id] => 1
            [parent_id] => 0
        )

    [1] => Array
        (
            [id] => 2
            [parent_id] => 1
        )

    [2] => Array
        (
            [id] => 3
            [parent_id] => 1
        )

    [3] => Array
        (
            [id] => 4
            [parent_id] => 3
        )

)