【发布时间】:2011-09-02 13:58:47
【问题描述】:
我想要一张这样的 cmets 表
id | comment | parent_id
--------------------------
1 text1 0
2 text2 1
3 text3 2
4 text4 3
5 text5 3
6 text6 5
我想构造一个数组来显示父母和孩子的层次结构。这棵树应该可以追溯到不确定的世代。我不想使用嵌套 foreach 循环,因为我不确定它有多深。这就是我在这里的原因,我不确定此类问题的最佳实践。我还想显示数组中的深度。下面是一个例子。它与上表并没有真正的关系,但希望能让您了解我需要什么。
array(
"depth"=> 4
"parent" => array(
"id"=> 1,
"comment" => "sometext1"
"child_count" => 2,
"children" => array(
0 => array(
"id" => 2
"comment" => "sometext2",
"child_count" => 0,
"children" => null
),
1 => array(
"id" => 3
"comment" => "sometext3"
"child_count" => 1,
"children" => array(
0 => array(
"id" => 2
"comment" => "sometext2",
"child_count" => 2,
"children" => array(
0 => array(
"id" => 2
"comment" => "sometext2",
"child_count" => 0,
"children" => null
),
1 => array(
"id" => 2
"comment" => "sometext2",
"child_count" => 1,
"children" => array(
"id" => 2
"comment" => "sometext2",
"child_count" => 0,
"children" => null
)
)
)
)
)
)
)
)
我打算使用 foreach 并执行一条 SQL 语句来检索该父/子的孩子。即
$sql = "SELECT * FROM comments WHERE parent = $parent_id";
我并不是真的在寻找所有这些的代码,只是一个伪代码解决方案。
【问题讨论】:
-
请看一下我的回答,我提供了一种在 PHP 上执行此操作的超级简单的方法。实际上效果很好。
-
你太棒了。谢谢。我确实很欣赏@Layke 方法,但可能需要我一点时间来理解它。同时我会接受你的回答。
标签: php multidimensional-array