0

我假装在一个层次结构中显示这个多维数组,在他们的父母下面显示孩子的评论。

$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() 提供的参数无效”

4

2 回答 2

0

我认为您的代码有问题。

步骤:
1. 调用loopComments
2.第一次在loopComments中调用printPost。 3. 在 printPost 中使用注释但在printPost中没有定义(在printPost外的调用函数loopComments中定义。)

所以,问题是:您应该在printPost foreach
循环中 使用变量$posts而不是$comments

于 2013-01-12T14:45:58.930 回答
0

在您的printPost()函数中,您需要一个参数来解析注释变量,以便在函数内使用该数组

function printPost($post, $comments) {}

当你打电话给它时,你会有

function loopComments($comments, $parent) {
    foreach ($comments as $post) {
        if ($post[parent_id] == $parent) {      
            printPost($post, $comments);
        }
    }
}
于 2013-01-12T14:38:22.527 回答