首先,我们需要了解什么是树结构。树结构是一种非线性数据结构,由节点和边组成,节点之间存在层次关系。我们通常将树的最上方节点称为根节点,将没有子节点的节点称为叶子节点。
下面是一个简单的树状数据结构:
{
"id": 1,
"name": "Node 1",
"children": [
{
"id": 2,
"name": "Node 1.1",
"children": [
{
"id": 3,
"name": "Node 1.1.1",
"children": []
},
{
"id": 4,
"name": "Node 1.1.2",
"children": []
}
]
},
{
"id": 5,
"name": "Node 1.2",
"children": [
{
"id": 6,
"name": "Node 1.2.1",
"children": []
}
]
}
]
}
要实现一个能嵌套任意层的PHP树代码,我们可以使用递归来将传入的数据转换成树状结构。下面是一个示例代码:
function buildTree($flat) {
$grouped = array_reduce($flat, function($carry, $item) {
$carry[$item['parent_id']][] = [
'id' => $item['id'],
'name' => $item['name'],
'children' => []
];
return $carry;
}, []);
$fnBuilder = function(&$node) use (&$fnBuilder, $grouped) {
$node['children'] = isset($grouped[$node['id']])
? $grouped[$node['id']]
: [];
foreach ($node['children'] as &$child) {
$fnBuilder($child);
}
};
$tree = $grouped[null];
foreach ($tree as &$node) {
$fnBuilder($node);
}
return $tree;
}
这个示例代码接受一个类似下面的扁平化结构:
[
['id' => 1, 'name' => 'Node 1', 'parent_id' => null],
['id' => 2, 'name' => 'Node 1.1', 'parent_id' => 1],
['id' => 3, 'name' => 'Node 1.1.1', 'parent_id' => 2],
['id' => 4, 'name' => 'Node 1.1.2', 'parent_id' => 2],
['id' => 5, 'name' => 'Node 1.2', 'parent_id' => 1],
['id' => 6, 'name' => 'Node 1.2.1', 'parent_id' => 5],
]
如果我们将上面的示例数据传入buildTree函数,它将会返回一个树状结构,如下所示:
[
[
'id' => 1,
'name' => 'Node 1',
'children' => [
[
'id' => 2,
'name' => 'Node 1.1',
'children' => [
[
'id' => 3,
'name' => 'Node 1.1.1',
'children' => [],
],
[
'id' => 4,
'name' => 'Node 1.1.2',
'children' => [],
],
],
],
[
'id' => 5,
'name' => 'Node 1.2',
'children' => [
[
'id' => 6,
'name' => 'Node 1.2.1',
'children' => [],
],
],
],
],
],
]
另一个示例代码是基于对象实现的树状结构。下面是示例代码:
class TreeNode {
public $id;
public $name;
public $children;
public function __construct($id, $name) {
$this->id = $id;
$this->name = $name;
$this->children = [];
}
public function addChild(TreeNode $node) {
$this->children[] = $node;
}
}
function buildTree($flat) {
$grouped = array_reduce($flat, function($carry, $item) {
$carry[$item['parent_id']][] = new TreeNode(
$item['id'],
$item['name']
);
return $carry;
}, []);
$fnBuilder = function($node) use (&$fnBuilder, $grouped) {
$node->children = isset($grouped[$node->id])
? $grouped[$node->id]
: [];
foreach ($node->children as $child) {
$fnBuilder($child);
}
};
$tree = new TreeNode(null, '');
$tree->children = $grouped[null];
foreach ($tree->children as $node) {
$fnBuilder($node);
}
return $tree->children;
}
此示例与前一个示例类似,但是使用了一个名为TreeNode的类来表示树节点。与前一个示例不同的是,这个函数返回的树节点本身而不是它们的属性(例如ID或名称)。
总的来说,要创建一个能嵌套任意层次的树结构,我们可以使用递归和循环两种方法。以上两个示例代码都是使用递归来生成嵌套树结构。如果使用循环,需要使用堆栈等数据结构才能实现。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:PHP树的代码,可以嵌套任意层 - Python技术站