我假装在一个层次结构中显示这个多维数组,在他们的父母下面显示孩子的评论。
$comments = Array
(
[0] => Array
(
[id] => 1
[text] => What is the capital of Japan?
[parent_id] => 0
)
[1] => Array
(
[id] => 2
[text] => What is the capital of Canada?
[parent_id] => 0
)
[2] => Array
(
[id] => 3
[text] => I think is Kyoto
[parent_id] => 1
)
[3] => Array
(
[id] => 4
[text] => You are wrong, is Tokyo
[parent_id] => 3
)
我在这里搜索了很多答案,但其中大多数都涉及对 DB 的多个查询,或者数组中不必要的子级字段。一个非常简单高效的循环函数就可以让它运行起来。我不是专家,我使用的是非常基本的代码,但这次效果不佳:
让我们发出一个带有仅显示父评论的函数的初始循环(父母有 [parent_id]=0)
echo '<ol>';
loopComments($comments, 0);
echo '</ol>';
以下是功能:
function loopComments($comments, $parent) {
foreach ($comments as $post) {
if ($post[parent_id] == $parent) {
printPost($post);
}
}
}
//The function below prints the post and searches for related answers
//sadly FAILS when looping again!
function printPost($post) {
echo "<li>".$post['text']."</li>";
loopComments($comments, $post['parent_id']);
}
可悲的是,我收到“警告:为 foreach() 提供的参数无效”