有两种方法可以在 PHP 中创建树状结构图:使用嵌套循环或使用递归。嵌套循环方法创建一个数组来存储节点和它们之间的关系,然后遍历数组以生成树状结构图。递归方法使用一个递归函数,根据节点的深度生成缩进,并遍历其子节点以生成子节点的树状结构图。

如何使用 PHP 创建树状结构图
PHP 中有多种方法可以创建树状结构图,本文将介绍两种最常用的方法:使用嵌套循环和使用递归。
方法 1:嵌套循环
示例代码:
立即学习“PHP免费学习笔记(深入)”;
<code class="php">$nodes = [
[
'id' => 1,
'parent_id' => null,
'children' => [2, 3]
],
[
'id' => 2,
'parent_id' => 1,
'children' => []
],
[
'id' => 3,
'parent_id' => 1,
'children' => []
],
];
function createTree($nodes) {
$tree = '<ul>';
foreach ($nodes as $node) {
$tree .= '<li>' . $node['id'];
if (!empty($node['children'])) {
$tree .= createTree($node['children']);
}
$tree .= '</li>';
}
$tree .= '</ul>';
return $tree;
}
echo createTree($nodes);</code>方法 2:递归
示例代码:
立即学习“PHP免费学习笔记(深入)”;
<code class="php">function createTree($nodes, $depth = 0) {
$tree = '';
foreach ($nodes as $node) {
$tree .= '<li style="padding-left:' . $depth * 10 . 'px">' . $node['id'] . '</li>';
if (!empty($node['children'])) {
$tree .= createTree($node['children'], $depth + 1);
}
}
return $tree;
}
$nodes = [
[
'id' => 1,
'parent_id' => null,
'children' => [2, 3]
],
[
'id' => 2,
'parent_id' => 1,
'children' => []
],
[
'id' => 3,
'parent_id' => 1,
'children' => []
],
];
echo createTree($nodes);</code>以上就是php如何写树状结构图的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号