简体   繁体   English

在php中用分支构建树

[英]Build tree with branches in php

I have $categories variable returns the following JSON data. 我有$ categories变量返回以下JSON数据。 I'd like to build a Tree->Branches in Php from this variable. 我想从此变量在Php中构建Tree-> Branches。 Any idea? 任何想法?

+Public +公共
- Electonics -电子学
.....- Computer .....- 电脑
........+ iPad-Tablets ........ + iPad-平板电脑
.....+ 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"
    }
]
}

This solution works for my problem. 此解决方案适用于我的问题。 Thanks @DanMiller 谢谢@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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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