从PHP数组中获取目录树

时间:2018-02-01 00:00:18

标签: php arrays treeview

我试图显示一个树文件结构,我发现了许多功能,所有这些功能都将目录作为参数,扫描它并应用一些对我没有帮助的逻辑因为我试图从转换为关联数组的JSON对象中做到这一点。

在这里您可以看到基本的JSON结构:

"categories": [
   {
       "project-id": "666",
       "parent-id": "", //This means it is a parent category
       "name": "Parent category name",
       "count": "0",
       "id": "3668",  //This id value will be used in the parent-id  key on the child element 
       "elements_count": "0",
       "type": "FileCategory"
   },
   {
       "project-id": "666",
       "parent-id": "3668"
       "name": "Children category name"
       "id": "4587" 
       etc..
   }, 

这里是PHP数组的一部分

array(2) { ["categories"]=> array(58) { 
[0]=> array(7) {
["project-id"]=> string(3) "666" 
["parent-id"]=> string(7) "3548745" 
["name"]=> string(13) "category name" 
["count"]=> string(1) "0" 
["id"]=> string(4) "3668" 
["elements_count"]=> string(1) "0" 
["type"]=> string(12) "FileCategory" }
[1]=> array(7) {
["project-id"]=> string(6) "667"
etc...
}

目前,我只想弄清楚如何将子文件夹(类别)放在它所属的位置。

例如:

for ($i=0; $i < $categoriesLenght; $i++) {
 if (empty($json_output['categories'][$i]['parent-id'])){ //if it has no parent then it is a "root" folder
        echo "<li class=\"root-directory\">" .$json_output['categories'][$i]['parent-id'] . "</li>";
    } else { //it is a subdirectory, but of what other category? How should I put it on the right place?
        echo "<li class=\"sub-directory\">" .$json_output['categories'][$i]['parent-id'] . "</li>";
    }

我想要的输出(目前)将是这样的:

Parent => 
      Child =>
           Child =>
      Child =>  
Parent => 
      Child =>
Parent => 

如何在其所属的类别中打印(或放置)子目录(任何级别)?我知道也许我应该使用parent-id键,但我无法弄清楚如何。

0 个答案:

没有答案