【问题标题】:Build tree with branches in php在 php 中构建带有分支的树
【发布时间】:2017-05-15 18:14:55
【问题描述】:

我有 $categories 变量返回以下 JSON 数据。我想用这个变量在 PHP 中构建一个 Tree->Branches。有什么想法吗?

+公开
- 电子学
.....- 电脑
........+ iPad-平板电脑
.....+ 灯
.....+ 家用电器
+ 运动

{
"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"
    }
]
}

【问题讨论】:

  • 在你可以操作这些数据之前,你需要使用json_decode:php.net/manual/en/function.json-decode.php
  • 我同意 Josan 的观点,你应该先使用 json_decode 来获取嵌套数组格式,然后才能轻松操作数据
  • 请显示所需的结果究竟是什么样的。
  • 检查:onetwothree
  • @DanMiller 谢谢。第三种解决方案对我有用。

标签: php sorting multidimensional-array parent-child recursive-datastructures


【解决方案1】:

此解决方案适用于我的问题。谢谢@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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-16
    • 2014-06-18
    • 2016-12-28
    • 1970-01-01
    相关资源
    最近更新 更多