amy burgess amy burgess - 1 month ago 7
PHP Question

How to add a parent ID to every child in a array? php

Hi guys I was wondering how can I add a parent ID in the children?

Ex: MY_ARRAY

(
[id] => 4
[children] => Array
(
[0] => Array
(
[id] => 18
[children] => Array
(
[0] => Array
(
[id] => 21
)
[1] => Array
(
[id] => 22
)
)
)
[1] => Array
(
[id] => 19
)
[2] => Array
(
[id] => 20
[children] => Array
(
[0] => Array
(
[id] => 26
)
)
)
)
)


And as of now these are the codes that I did but still not giving me the correct result.

$in = MY_ARRAY
function generateArray($in, $out, $parent = 0, $prev_par = 0){
foreach($in as $key => $value) {
$childs = false;
if(isset($value['children'])){ // if there is children
$childs = $value['children'];
unset($value['children']);
}
if($prev_par != $parent){
$prev_par = $parent;
}
else{
$prev_par = $prev_par;
}
$out[] = array($value['id'],$parent,$prev_par);
if($childs){
$parent = $value['id'];
$out = $this->generateArray($childs, $out, $parent, $prev_par);
}
}
return $out;
}





I would need to add an Parent ID becaue as of now it I can retrive their heirarchy without displaying correnct Parent ID.

The output could look like this. As long as I can add the Parent ID.

[id] => 4
[P_id] => 0
[children] => Array
(
[0] => Array
(
[id] => 18
[P_id] => 4
[children] => Array
(
[0] => Array
(
[id] => 21
[P_id] => 18
)
[1] => Array
(
[id] => 22
[P_id] => 18
)
)
)
[1] => Array
(
[id] => 19
[P_id] => 4
)

[2] => Array
(
[id] => 20
[P_id] => 4
[children] => Array
(
[0] => Array
(
[id] => 26
[P_id] => 20
)
)
)
)
)


Need really help here thanks guys...

Answer

Your problem is solved, check it. The function is recursively push p_id and another point is if the array contain numeric index then it will skip to push p_id.

Function is:

function generateArray($in, $parent = 0){
  foreach ($in as $key => $value) {
    if(is_numeric($key)){
        $in = $value;
        $out[$key] = generateArray($in, $parent);
    }else{
      $out[$key]=$value;
      if($key=="id"){
        $out['p_id']=$parent;
        $parent=$value;
      }elseif($key=="children"){
        $in = $value;
        $out[$key] = generateArray($in, $parent);
      }
    }
  }
  return $out;
}

Working example:

$my_array =array(
  'id'=> 4,
  'children'=> Array(
    '0'=> Array(
      'id'=> 18,
      'children'=> Array(
          '0'=> Array(
            'id'=> 21,
          ),
          '1'=> Array(
            'id'=> 22,
          ),
        ),
    ),
    '1'=> Array(
      'id'=> 19,
    ),
    '2'=> Array(
      'id'=> 20,
      'children'=> Array(
        '0'=> Array(
          'id'=> 26,
        ),
      ),
    ),
  )
);

$newarray = generateArray($my_array);
print_r($newarray);