我有一个包含菜单项的数组。每个项目都有其parent_id。我正在搜索并尝试了很多个小时,但无法弄清楚如何递归遍历数组。我不擅长递归。
我试过使用以下帖子中的代码。它生成了html菜单,但它错过了第一条记录,我也想要一个数组,所以我可以从数组中制作自定义的html菜单。
Using recursion to build navigation
我从其他帖子尝试过此代码,但它返回空数组。
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;
}
数据阵列:
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/
)
)
期望的结果:
home - page
sub_page
inner_page
请非常感谢任何帮助。
答案 0 :(得分:1)
它应该做的是首先打印0作为父母的那些,为每个人找到它的孩子,并为每个孩子重新开始。
类似的东西:
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>
答案 1 :(得分:0)
Thanks to Gabriel, I have used his method to create an other method that returns an array for the menu.
$data = array(
array('id'=>1, 'parent_id'=>-1, 'url_title'=>'home', 'url'=>'/home'),
array('id'=>2, 'parent_id'=>0, 'url_title'=>'page-one', 'url'=>'/page-one'),
array('id'=>3, 'parent_id'=>2, 'url_title'=>'sub-page', 'url'=>'/sub-page'),
array('id'=>4, 'parent_id'=>3, 'url_title'=>'inner-page', 'url'=>'/inner-page')
);
function menu_html($data,$parent=-1) {
$res='';
foreach($data as $e) {
if($e['parent_id']==$parent||($parent==-1&&$e['parent_id']==0)) {
$res.='<li>'.$e['url'];
$sub=menu_html($data,$e['id']);
if($sub) $res.='<ul>'.$sub.'</ul>';
$res.='</li>';
}
}
return $res;
}
echo '<ul>'.menu_html($data).'</ul>';
function menu_array($data,$parent=-1) {
$res=array();
foreach($data as $e) {
if($e['parent_id']==$parent||($parent==-1&&$e['parent_id']==0)) {
$res[$e['url']] = $e;
$sub=menu_array($data, $e['id']);
if($sub) $res[$e['url']]['sub-nav'] = $sub;
}
}
return $res;
}
echo "<pre>";
print_r(menu_array($data));
echo "</pre>";
Output:
/home
/page-one
/sub-page
/inner-page
Array
(
[/home] => Array
(
[id] => 1
[parent_id] => -1
[url_title] => home
[url] => /home
)
[/page-one] => Array
(
[id] => 2
[parent_id] => 0
[url_title] => page-one
[url] => /page-one
[sub-nav] => Array
(
[/sub-page] => Array
(
[id] => 3
[parent_id] => 2
[url_title] => sub-page
[url] => /sub-page
[sub-nav] => Array
(
[inner-page] => Array
(
[id] => 4
[parent_id] => 3
[url_title] => inner-page
[url] => inner-page
)
)
)
)
)
)