我有这个名为$nested的数组(这是一个很长的数组,但我试图获得一个全面的方案):
Array
(
[1] => Array
(
[id] => 1
[parent] => 0
[title] => Page 1
)
[2] => Array
(
[id] => 2
[parent] => 0
[title] => Page 2
)
[3] => Array
(
[id] => 3
[parent] => 0
[title] => Page 3
)
[4] => Array
(
[id] => 4
[parent] => 0
[title] => Page 4
)
[5] => Array
(
[id] => 5
[parent] => 0
[title] => Page 5
)
[6] => Array
(
[id] => 6
[parent] => 1
[title] => Page 1-1
)
[7] => Array
(
[id] => 7
[parent] => 1
[title] => Page 1-2
)
[8] => Array
(
[id] => 8
[parent] => 1
[title] => Page 1-3
)
[9] => Array
(
[id] => 9
[parent] => 2
[title] => Page 2-1
)
[10] => Array
(
[id] => 10
[parent] => 2
[title] => Page 2-2
)
[11] => Array
(
[id] => 11
[parent] => 2
[title] => Page 2-3
)
[12] => Array
(
[id] => 12
[parent] => 3
[title] => Page 3-1
)
[13] => Array
(
[id] => 13
[parent] => 3
[title] => Page 3-2
)
[14] => Array
(
[id] => 14
[parent] => 4
[title] => Page 4-1
)
[15] => Array
(
[id] => 15
[parent] => 6
[title] => Page 1-1-1
)
[16] => Array
(
[id] => 16
[parent] => 6
[title] => Page 1-1-2
)
[17] => Array
(
[id] => 17
[parent] => 6
[title] => Page 1-1-3
)
[18] => Array
(
[id] => 18
[parent] => 7
[title] => Page 1-2-1
)
[19] => Array
(
[id] => 19
[parent] => 7
[title] => Page 1-2-2
)
[20] => Array
(
[id] => 20
[parent] => 7
[title] => Page 1-2-3
)
[21] => Array
(
[id] => 21
[parent] => 9
[title] => Page 2-1-1
)
[22] => Array
(
[id] => 22
[parent] => 9
[title] => Page 2-1-2
)
[23] => Array
(
[id] => 23
[parent] => 9
[title] => Page 2-1-3
)
)
有了这个递归函数:
function recursive($parent, $array) {
$has_children = false;
foreach($array as $key => $value) {
if ($value['parent'] == $parent) {
if ($has_children === false && $parent) {
$has_children = true;
echo '<ul>' ."\n";
}
echo '<li>' . "\n";
echo '<a href="/page.php?id=' . $value['id'] . '">' . $value['title'] . '</a>' . " \n";
echo "\n";
recursive($key, $array);
echo "</li>\n";
}
}
if ($has_children === true && $parent) echo "</ul>\n";
}
<ul><?php echo recursive(0, $nested); ?></ul>
我很容易得到这个输出:
> Page 1
> Page 1-1
> Page 1-1-1
> Page 1-1-2
> Page 1-1-3
> Page 1-2
> Page 1-2-1
> Page 1-2-2
> Page 1-2-3
> Page 1-3
> Page 2
> Page 2-1
> Page 2-1-1
> Page 2-1-2
> Page 2-1-3
> Page 2-2
> Page 2-3
> Page 3
> Page 3-1
> Page 3-2
> Page 4
> Page 4-1
> Page 5
到现在为止还挺好.
现在,我不想一次显示整个树,但是当用户点击页面/子页面时会更深入,如下所示:
URL:http://www.example.com/page.php,初始状态(“展开”所有带有parent = 0的项目)
> Page 1
> Page 2
> Page 3
> Page 4
> Page 5
URL:http://www.example.com/page.php?id=1(展开parent = 1的所有项目)
> Page 1
> Page 1-1
> Page 1-2
> Page 1-3
> Page 2
> Page 3
> Page 4
> Page 5
URL:http://www.example.com/page.php?id=6(展开parent = 6的所有项目)
> Page 1
> Page 1-1
> Page 1-1-1
> Page 1-1-2
> Page 1-1-3
> Page 1-2
> Page 1-3
> Page 2
> Page 3
> Page 4
> Page 5
等等
似乎任务无法完成,请帮忙吗?
提前致谢
解决方法:
你快到了.只是一个小问题:而不是递归($key,$array),你需要递归($key 1,$array).尽管如此,正如其他人所说的那样,如果您只使用PHP生成整个输出然后使用javascript控制它,那将会更好.每次用户点击项目时重新加载页面实际上都不是一个好的用户体验.