【问题标题】:PHP - loop inside a loop for hierarchical nested questions and answersPHP - 在循环内循环分层嵌套问题和答案
【发布时间】:2013-01-12 14:33:16
【问题描述】:

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

$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 的多个查询,或者数组中不必要的子级字段。一个非常简单高效的循环函数就可以让它运行起来。我不是专家,我使用的是非常基本的代码,但这次效果不佳:

让我们发出一个带有仅显示父 cmets 的函数的初始循环(父母有 [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() 提供的参数无效”

【问题讨论】:

    标签: php loops parent-child


    【解决方案1】:

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

    function printPost($post, $comments) {}
    

    当你调用它时,你就会拥有

    function loopComments($comments, $parent) {
        foreach ($comments as $post) {
            if ($post[parent_id] == $parent) {      
                printPost($post, $comments);
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      我认为你的代码有问题。

      步骤:
      1. 调用loopComments
      2. 第一次在 loopComments 中调用 printPost
      3、在printPost中使用cmets,但在printPost中没有定义(在调用函数loopComments中定义) > printPost 之外。)

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

      【讨论】:

      • 我刚刚解决了,我只是在第一个中集成了secnd功能!
      猜你喜欢
      • 1970-01-01
      • 2017-09-20
      • 1970-01-01
      • 1970-01-01
      • 2021-05-17
      • 2015-12-05
      • 2021-01-10
      • 1970-01-01
      • 2021-05-30
      相关资源
      最近更新 更多