Home > front end >  How to format data to tree structure to return in laravel - API
How to format data to tree structure to return in laravel - API

Time:06-24

I have a database like that: Database

Let me explain about database

For example: the first node has parent_id is 0 with id = 1
2 children of id = 1 is 2 and 3. So parent_id = 1

So I want to return response tree structure like that:

[
    {
        id: 1,
        name_en: Animal & Pet Supplies,
        name_ja: ...,
        child: [
                     {
                         id: 2,
                         name_en: ...,
                         name_ja: ...,
                         child: [ 
                                   ... so on
                                ]
                     },
                     {
                         id: 2,
                         name_en: ...,
                         name_ja: ...,
                         child: [ 
                                   ... so on
                                ]
                     }
               ]
    }
]

Please give me a solution, thank you so much.

CodePudding user response:

Try this coding

//Recursive function
    public function tree($id,$parentID){
        $animals = DBName::where('id',$id)->orderBy('name_en','ASC')->get();
        $ml = [];
        foreach($animals as $row) {
            $data = DBName::where('id','=',$row->id)->where('name_ja','=',$parentID)->first();
            if($data){
                $ml[] = $row;
                $Row = DBName::where('parent_id',$row->id)->first();
                if($Row){
                    $row->child = $this->tree($row->id,$parentID);
                }else{
                    $row->child = [];
                } 
            }
        }
        return $ml;
    }
  • Related