0

I am bit stuck with my following code as it is not including an element inside the array which has no child.My code is

$arr = array
( 
    array
        (
            'id' => 66,
            'parent_id' => 26,
            'ptitle' => 'slider container',

        )
,
    array
        (
            'id' => 47,            
            'parent_id' => 26,
            'ptitle' => 'Landing Page',

        )
,
    array
        (
            'id' => 48,         
            'parent_id' => 66,
            'ptitle' => 'Link 1',

        )
,
    array
        (
            'id' => 49,            
            'parent_id' => 66,
            'ptitle' => 'Link 2',

        )
,
);

$new = array();
foreach ($arr as $a){
    $new[$a['parent_id']][] = $a;
}

$tree = createTree($new, array($arr[0]));
echo "<pre>";
print_r($tree);
echo "</pre>";

function createTree(&$list, $parent){
    $tree = array();

    foreach ($parent as $k=>$l){

        if(isset($list[$l['id']])){
            $l['children'] = createTree($list, $list[$l['id']]);
        }
        $tree[] = $l;
    } 
    return $tree;
}

As the looping starts from first element of the array which is $arr[0] so that's why it is not considering the element whose id is 47 but I need this to be included in final array.

Any help is highly appreciated.

SOLVED

Raj
  • 1,377
  • 6
  • 23
  • 48
  • I have posted the code. It's all there.Do you want to see the final output of the tree? – Raj Sep 28 '14 at 18:42
  • @ialarmedalien Scroll down - the loop code and the createTree function are after the data structure. – TML Sep 28 '14 at 18:46
  • @deceze Thanks for the duplicate link and I have gone through it.Its not the same scenario as my case is.In that ref post the parent starts from 0 so it gives you the children of that parent but in my case the parent is not 0 or null.So the if else part will not work and gives me a blank array. – Raj Sep 28 '14 at 18:57
  • Is this a correct encapsulation of the data structure you are hoping to have at the end of this process? http://imgur.com/jUTqXHX – TML Sep 28 '14 at 19:08
  • I am really sorry @deceze. It's my mistake. I didn't read the comments there. It's all working great now. Once again thanks for the link. – Raj Sep 28 '14 at 19:33

0 Answers0