1

I am trying to create a multidimentional array from a MySQL result. It is a parent child relationship. Something like this.

$navArr = array();
$pageNav = Page::where('parent_id', 0)->orderBy('nav_order', 'asc')->get();
foreach($pageNav as $parent) {
    $navArr[$parent->page_id] = $parent;
    pageNavChildren = Page::where('parent_id', $parent->page_id)->orderBy('nav_order', 'asc')->get();
    if($pageNavChildren) {
        foreach($pageNavChildren as $child) {
            $navArr[$parent->page_id]['childrens'] = array($child->page_id => $child);
        }
    }
}

It gives me an array but the array only has the last child in it. My guess is it getting over written in the loop. I need an array with all the parents then if the parent has a child set the children key and within it I need the each child array under that one key.

1 Answer 1

1

Change this:

 if($pageNavChildren) {
     foreach($pageNavChildren as $child) {
          $navArr[$parent->page_id]['childrens'] = array($child->page_id => $child);
      }
  }

To:

if($pageNavChildren) {
    foreach($pageNavChildren as $child) {
        $navArr[$parent->page_id]['childrens'][] = array($child->page_id => $child);
    }
}
Sign up to request clarification or add additional context in comments.

7 Comments

Hi @aldrin27 I tried that but got the following error. Indirect modification of overloaded element of App\Page has no effect
Can you print_r($pageNav);?
I posted the error I got. I cannot print_r the array because with Laravel it posts a ton of hidden fields I would not even be able to copy and paste it in here because of character limitations but I did post the error I received above.
I only want to know the returned data of $pageNav = Page::where('parent_id', 0)->orderBy('nav_order', 'asc')->get();
I would paste it if I could but with Laravel its not a simple data dump. I can't just print_r copy and paste. It has thousands of characters.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.