Webtect
Webtect

Reputation: 839

create multidimentional array from mysql data using Laravel 5

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.

Upvotes: 1

Views: 73

Answers (1)

aldrin27
aldrin27

Reputation: 3407

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);
    }
}

Upvotes: 1

Related Questions