samedi 14 septembre 2019

Store Dynamic Menu data into a json from MySQL Database using PHP

I have a self referencing table storing dynamic menu data like following.

|----|----------------|---------------------|------------| 
|id  |  name          | link                | parent_id  |
|----|----------------|---------------------|------------| 
|1   |  Setup         | NULL                | NULL       |
|----|----------------|---------------------|------------| 
|2   |  Common_Setup  | NULL                | 1          |
|----|----------------|---------------------|------------| 
|3   |  Management    | NULL                | NULL       |
|----|----------------|---------------------|------------| 
|4   |  Gender        | setup/gender        | 2          |
|----|----------------|---------------------|------------| 
|5   |  Approval      | management/approval | 3          |
|----|----------------|---------------------|------------| 
|6   |  EEE           | eee                 | NULL       |
|----|----------------|---------------------|------------|

Now i want to store them as a json in PHP(Laravel) variable, like the following structure,

[
   {
       id       : 1,
       title    : 'Setup',
       children : [
           {
               id       : 2,
               title    : 'Common_Setup',
               children : [
                   {
                   }
               ]

           }
       ]
   }
] 

As, there is no limit for the children level layer, i think its better to call a recursive method or something like this.

function hierarchy($allPage, $parent = 0) {
    foreach ($allPage as $page) {
        if ($page->parent_id === NULL) $page->parent_id = 0;
        if ($page->parent_id === $parent) {
            $children = hierarchy($allPage, $page->id);
        }
    }
}


function getPages()
{
    $allPage = Page::all():
    $dynamicMenu = hierarchy($allPage, 0);
    echo "last: ".$dynamicMenu;
}

In the $dynamicMenu, i want to store the final JSON structure. Can anyone tell me how i can get this desirable structure ?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/31oTJ5E
via IFTTT

Aucun commentaire:

Enregistrer un commentaire