I have a collction of posts I´l like to show in a table. Each post has an id and a parent_id.
I want to loop through the table with a nested foreach, but I dont get it to work. My idea is to loop through each post, print the name and stuff, and also find all it´s children (by looping through each post and see if the childs parent id is equal to my id.)
My code is:
$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;
}
}
}
}
The problem is, the first loop does only run once. If I delete the second foreach-loop, the first one runs correctly.
Why is this happening, and how do I solve it?
ADDED: The post itself is like a blog post, it contains the following: id, title, body, compact, parent_id. Where id is the unique id, title and body as title and body to the blog post, compact as a short name used for the url, an the parent id to tell who the post is lying under, ie. Im a child to my parent.
Since the user should have all the possibility to move around the posts and put the posts in a menu, think of the top level posts as menu items, and the once that have a parent as the submenu item.
$childPost,$allPostscontain? what is the relation?$posts;, it will become easy for us to understand your problem