我有一个我想在表格中显示的帖子的整理。每个帖子都有一个 ID 和一个parent_id。
我想用嵌套的foreach循环浏览表,但我没有让它工作。我的想法是遍历每个帖子,打印名称和内容,并找到它的所有子项(通过循环浏览每个帖子,看看孩子的父母 ID 是否等于我的 ID。
我的代码是:
$allPosts = $posts;
foreach ($posts as $post) {
if ($post->parent_id == 0){ //0 means highest level, no parent
echo $post->name;
$current_id = $post->id;
foreach ($allPosts as $childPost){
if($childPost->parent_id == $current_id){
echo $cihldPost->name;
}
}
}
}
问题是,第一个循环只运行一次。如果我删除第二个 foreach 循环,第一个循环将正常运行。
为什么会发生这种情况,我该如何解决?
添加:文章本身就像一篇博客文章,它包含以下内容:id、标题、正文、紧凑parent_id。其中id是唯一的id,标题和正文作为博客文章的标题和正文,紧凑作为用于URL的短名称,父ID告诉帖子躺在谁之下,即。我是我父母的孩子。
由于用户应该有可能在帖子周围移动并将帖子放在菜单中,因此将顶级帖子视为菜单项,将具有父级的帖子视为子菜单项。
我的想法是遍历每个帖子,打印名称和内容,并找到它的所有子项(通过循环浏览每个帖子,看看孩子的父母 ID 是否等于我的 ID。
目前,您只是尝试再次遍历同一对象。$allPosts
变量不是必需的。如果尝试遍历每个子元素,则需要在嵌套foreach
循环中使用$post
。
您当前正在执行以下操作:
$obj2 = $obj;
foreach ($obj as $child) {
foreach ($obj2 as $anotherchild) {
# code...
}
}
粗略地说,结构应如下所示:
foreach ($obj as $child) {
foreach ($child as $secondchild) {
# code...
}
}
使用您的代码:
foreach ($posts as $post) {
if ($post->parent_id == 0){ //0 means highest level, no parent
echo $post->name;
$current_id = $post->id;
foreach ($post as $childPost){
if($childPost->parent_id == $current_id){
echo $cihldPost->name; // <-- typo?
}
}
}
}
某种原因,foreach 无法处理我的控制器传递给我视图的$posts对象本身。但是,如果我将$posts保存在本地数组中,则一切都有效。我仍然不知道为什么我首先会遇到这个问题,所以请发表评论或提供更好的答案。
$mylist = array();
foreach($posts as $post) {
$listitem = array();
$listitem['id'] = $post->id;
$listitem['parent_id'] = $post->parent_id;
$listitem['title'] = $post->title;
$listitem['compact'] = $post->compact;
$mylist[] = $listitem;
}
foreach($mylist as $listitem){
#code..
foreach($mylist as $inneritem){
#code..
}
}
以下是我更改您的代码的方式:
$posts = array(
(object) array("parent_id" => 0, "id" => 1, "name" => 'Outer 1'),
(object) array("parent_id" => 0, "id" => 2, "name" => 'Outer 2'),
(object) array("parent_id" => 0, "id" => 3, "name" => 'Outer 3'),
(object) array("parent_id" => 0, "id" => 4, "name" => 'Outer 4'),
(object) array("parent_id" => 0, "id" => 5, "name" => 'Outer 5'),
(object) array("parent_id" => 1, "id" => 6, "name" => 'Inner 1.1'),
(object) array("parent_id" => 1, "id" => 7, "name" => 'Inner 1.2'),
(object) array("parent_id" => 4, "id" => 8, "name" => 'Inner 4.1'),
(object) array("parent_id" => 5, "id" => 9, "name" => 'Inner 5.2'),
(object) array("parent_id" => 5, "id" => 10, "name" => 'Inner 5.2'),
(object) array("parent_id" => 5, "id" => 11, "name" => 'Inner 5.3'),
);
$allPosts = $posts;
foreach ($posts as $post) {
if ($post->parent_id == 0){ //0 means highest level, no parent
echo $post->name . ' : ';
$current_id = $post->id;
foreach ($allPosts as $childPost){
if($childPost->parent_id == $current_id){
echo $childPost->name . ', ';
}
}
echo '<br>';
}
}
输出以下内容:
Outer 1 : Inner 1.1, Inner 1.2,
Outer 2 :
Outer 3 :
Outer 4 : Inner 4.1,
Outer 5 : Inner 5.2, Inner 5.2, Inner 5.3,
如果问题不在您的代码中(对我来说看起来不错,并且在我的计算机上也可以按预期工作(,则它可能出在 $posts
数组的结构中。尝试对变量使用var_dump
,以查看它们是否包含不完整或不正确的数据。