generate parent child relation from the array to print a multi-level menu?

Posted by Karthick Selvam on Programmers See other posts from Programmers or by Karthick Selvam
Published on 2012-12-13T07:47:26Z Indexed on 2012/12/13 11:19 UTC
Read the original article Hit count: 313

Filed under:
|
|
|

How to get parent child relation from this array to print a multi-level menu

 $menus = array
      (
        0 => array
            (   'id'=>0,
                'check' => 1,
                'display' =>'Arete Home',
                'ordering' => -10,
                'parent' => none,
            ),

        1 => array
            (
        'id'=>1,
                'check' => 1,
                'display' => 'Submit Paper',
                'ordering' => -10,
                'parent' => 2,
                'subordering' => -10,
            ),

        2 => array
            (
        'id'=>2,
                'check' => 1,
                'display' => 'Buy Now',
                'ordering' => -10,
                'parent' => 1,
                'subordering' => -10,
            ),

        1461 => array
            (
                'id'=>1461,
        'check' => 1,
                'display' => 'Where are We?',
                'ordering' => -10,
                'parent' => 2,
                'subordering' => -10,
            ),

        1463 => array
            (
        'id'=>1463,
                'check' => 1,
                'display' =>' About Me?',
                'ordering' => -10,
                'parent' => 2,
                'subordering' => -10,
            ),

        1464 => array
            (
        'id'=>1464,
                'check' => 1,
                'display' => 'About You?',
                'ordering' => -10,
                'parent' => 2,
                'subordering' => -10,
            ),

        1465 => array
            (
        'id'=>1465,
                'check' => 1,
                'display' => 'About who?',
                'ordering' => -10,
                'parent' => 1,
                'subordering' => -10,
            ),

    );

code sample:

foreach($menus as $id=>$values)
{ 
  $values['parent']=isset($values['parent']) ? $values['parent'] : 0;
  $menus[$values['parent']]['childs'][$id]=$values; unset($menus[$id]); 
} 
foreach($menus as $id1=>$value2)
{ 
  $value2['parent']=isset($value2['parent']) ? $value2['parent'] : 0;      
  $menus[$value2['parent']]['childs'][$id1]=$value2; unset($menus[$id1]); 
}

© Programmers or respective owner

Related posts about php

Related posts about recursion