Bsienn Bsienn - 7 months ago 21
PHP Question

create menu array recursively

I have a single array containing menu items. Each item have its parent_id. I am searching and trying for many hours but can't figure out how to traverse the array recursively. I'm not good at recursion.

I have tried to use the code from the following post. It generates the html menu but it misses the 1st record also I want an array so I can make custom html menu out of the array.

Using recursion to build navigation

I have tried this code from an other post but it returns empty array.

create_array(-1, $array);

function create_array($number, $data)
{
$result = array();
foreach ($data as $row)
{
if ($row['parent_id'] == $number)
{
$result[$row['id']] = create_array($row['id'], $data);
}
}
return $result;
}


data array:

Array
(
[0] => Array
(
[id] => 1
[parent_id] => -1
[url] => /home
)

[1] => Array
(
[id] => 2
[parent_id] => 0
[url] => /page
)

[2] => Array
(
[id] => 3
[parent_id] => 2
[url] => /page/sub_page
)

[3] => Array
(
[id] => 4
[parent_id] => 3
[url] => /page/sub_page/inner_page/
)

)


result desired:

home - page
sub_page
inner_page


Any help will be very appreciated please.

Answer

What it should do is start by printing the ones with 0 as parent, for each one find it's children and start again for each children.

Something like:

function menu($data,$parent=-1) {
    $res='';    
    foreach($data as $e) {
        if($e['parent_id']==$parent||($parent==-1&&$e['parent_id']==0)) { //Also search for 0 when parent is  -1 as are both the roots
            $res.='<li>'.$e['url']; //Or whatever you want to show
            $sub=menu($data,$e['id']);
            if($sub) $res.='<ul>'.$sub.'</ul>';
            $res.='</li>';
         }
    }
    return $res;
}

<ul><?=menu($data)?></ul>