0

I have $categories variable returns the following JSON data. I'd like to build a Tree->Branches in Php from this variable. Any idea?

+Public
- Electonics
.....- Computer
........+ iPad-Tablets
.....+ Lights
.....+ Home Applicances
+ Sport

{
"categories": [
    {
        "ID": 0,
        "Name": "Public",
        "Parent": 0,
        "created": null,
        "modified": "2017-03-13T15:16:58+00:00"
    },
    {
        "ID": 4,
        "Name": "Electronics",
        "Parent": 0,
        "created": "2017-03-13T15:18:21+00:00",
        "modified": "2017-03-13T15:18:21+00:00"
    },
    {
        "ID": 5,
        "Name": "Computer",
        "Parent": 4,
        "created": "2017-03-13T15:18:34+00:00",
        "modified": "2017-03-13T15:18:34+00:00"
    },
    {
        "ID": 12,
        "Name": "iPad-Tablets",
        "Parent": 5,
        "created": "2017-05-15T13:55:38+00:00",
        "modified": "2017-05-15T13:55:38+00:00"
    }
]
}
Majid Nasirinejad
  • 107
  • 1
  • 2
  • 13
  • Before you can manipulate this data, you will need to use `json_decode`: http://php.net/manual/en/function.json-decode.php – JJJ May 15 '17 at 18:19
  • I agree with Josan, you should use json_decode first to get in the nested array format and then it will be easy to manipulate the data – zenwraight May 15 '17 at 18:20
  • Please show what exactly the desired result looks like. – Roman Hocke May 15 '17 at 18:20
  • 1
    Check: [one](http://stackoverflow.com/questions/4196157/create-array-tree-from-array-list) [two](http://stackoverflow.com/questions/8840319/build-a-tree-from-a-flat-array-in-php) [three](http://stackoverflow.com/questions/14740429/flat-php-array-to-hierarchy-tree) – Alexey Chuhrov May 15 '17 at 19:33
  • @DanMiller Thanks. Third solution works for me. – Majid Nasirinejad May 16 '17 at 13:02

1 Answers1

0

This solution works for my problem. Thanks @DanMiller

function generatePageTree($datas, $parent = 0, $depth=0){               
    if($depth > 100) return ''; //Make sure not to have an endless recursion
    $tree = '<ul>';
    for($i=0, $ni=count($datas); $i < $ni; $i++){
        if($datas[$i]->Parent == $parent){
            $tree .= '<li>';
            $tree .= $datas[$i]->Name;
            $tree .= generatePageTree($datas, $datas[$i]->ID, $depth+1);
            $tree .= '</li>';
        }
    }
    $tree .= '</ul>';
    return $tree; 
}
$tree=generatePageTree($categoriesOptions);
echo $tree;
Majid Nasirinejad
  • 107
  • 1
  • 2
  • 13