我假裝在一個層次結構中顯示這個多維數組,顯示他們的父母下面的孩子評論。PHP - 循環內的循環嵌套的問題和答案
$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
)
我搜索了很多答案,以防萬一在這裏,但其中大多數涉及到幾個查詢數據庫,或陣列的unnecesary次級領域。一個非常簡單而有效的循環函數可以使其運行。我不是專家,但我使用的是非常基本的代碼,但這次運行不正常:
讓我們用一個函數發出一個初始循環,以僅顯示父註釋(父母[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()提供了無效的參數'
我剛解決了它,我只是在第一個中集成了secnd函數! –