简体   繁体   中英

How to insert child into parent as json from database in Laravel/PHP?

Here's my database table:

id   name               icon            parent_id
1    Account Settings   fa fa-cog       0
2    Support            fa fa-wrench    0
3    FAQ                fa fa-question  2
4    Contact            fa fa-phone     2

I'm trying to query menu list from database and return it as json format like below:

 [{
    "name": "Account Settings",
    "icon": "fa fa-cog"
  }, {
    "name": "Support",
    "icon": "fa fa-wrench",
    "children": [{
      "name": "FAQ",
      "icon": "fa fa-question"
    }, {
      "name": "Contact",
      "icon": "fa fa-phone"
    }]
  }]

However, I don't know how can I insert the child into the parent section.

My code as below:

$menu_list = MobMenu::all('name', 'icon', 'parent_id');

foreach ($menu_list as $data) {
   $child = MobMenu::find($data->parent_id);
}

return json_encode($menu_list);

How can I create "children" and insert it into the parent section ?

You can use this code.

$menu_list = MobMenu::all('name', 'icon', 'parent_id'); //without where condition
$menu_list = MobMenu::where('parent_id',0)->select('name','icon','parent_id')->get(); //with where condition

foreach ($menu_list as $key=>$data) {
   $menu_list[$key]['children'] = MobMenu::find($data->parent_id);
}

return json_encode($menu_list);

It will add children in menu_list array and you can convert it into json.

You may use the transform method

$menu_list = MobMenu::all();

$menu_list->transform(function ($item) {

    $children = MobMenu::where('parent_id', $item->id)
                        ->get(['name', 'icon']);

    if ($children->count()) {
        $item->children = $children;
    }

    return $item;
});

return json_encode($menu_list);

You can transform your current output to hierarchical

<?php
$results = [
  ["id"=>1,"name"=>"Account Settings","icon"=>'fa fa-cog',"parent_id"=>0],
  ["id"=>2,"name"=>"Support","icon"=>'fa fa-wrench',"parent_id"=>0],
  ["id"=>3,"name"=>"FAQ","icon"=>'fa fa-question',"parent_id"=>2],
  ["id"=>4,"name"=>"Contact","icon"=>'fa fa-phone',"parent_id"=>2]
 ];
 $final = array();
 foreach($results as $r){
   if($r['parent_id']){
     $final[$r['parent_id']]['children'][] = $r;
   }else{
     $final[$r['id']] = $r;
   }
 }

print_r($final);

?>

Live Demo

Output

Array
(
    [1] => Array
        (
            [id] => 1
            [name] => Account Settings
            [icon] => fa fa-cog
            [parent_id] => 0
        )

    [2] => Array
        (
            [id] => 2
            [name] => Support
            [icon] => fa fa-wrench
            [parent_id] => 0
            [children] => Array
                (
                    [0] => Array
                        (
                            [id] => 3
                            [name] => FAQ
                            [icon] => fa fa-question
                            [parent_id] => 2
                        )

                    [1] => Array
                        (
                            [id] => 4
                            [name] => Contact
                            [icon] => fa fa-phone
                            [parent_id] => 2
                        )

                )

        )

)

Make a new relationship callled children in your MobMenu model.

public function children()
{
    return $this->hasMany(MobMenu::class, 'parent_id','id');
}

Then in controller, use with() to get the childrens data.

$menu_list = MobMenu::with('children')->where('parent_id',0)->get()->toArray();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM