如何从平面数组制作树 - php


How to make a tree from a flat array - php

我试图以可以浏览的树结构表示从 Amazon S3 存储桶返回的整个数组。

数组示例如下

$files[0] = 'container/798/';
$files[1] = 'container/798/logo.png';
$files[2] = 'container/798/test folder/';
$files[3] = 'container/798/test folder/another folder/';
$files[4] = 'container/798/test folder/another folder/again test/';
$files[5] = 'container/798/test folder/another folder/test me/';
$files[6] = 'container/798/test two/';
$files[7] = 'container/798/test two/logo2.png';

这就是我正在努力实现的目标

https://i.stack.imgur.com/HBjvE.png   

到目前为止,我只实现了不同的文件和文件夹,但没有实现父子关系的不同级别。上面提到的数组驻留在$keys['files']中。代码如下

$keys = json_decode($result,true);
$folders = array();
$files = array();
$i =0;
foreach ($keys['files'] as $key){
    if(endsWith($key, "/")){
        $exploded = explode('container/'.$_SESSION['id_user'].'/',$key);
        if(!empty($exploded[1]))
        $folders[$i]['name'] = substr($exploded[1],0,-1);
    }
    else{
        $exploded = explode('container/'.$_SESSION['id_user'].'/',$key);
        $files[$i]['name'] = $exploded[1];
        $files[$i]['size'] = "";
        $files[$i]['date'] = "";
        $files[$i]['preview_icon'] = "";
        $files[$i]['dimensions'] = "";
        $files[$i]['url'] = "";
    }
    $i++;
}

这是代码,只是为了表明我正在尝试,但它不完整或不准确。我不知道如何处理一个逻辑,可以给我我正在展示图片的层次结构。任何帮助将不胜感激。

我不知道

这是否是执行此操作的"正确"方法,但是如果您想制作递归结构,那么简单的方法是使用递归函数:

$root = array('name'=>'/', 'children' => array(), 'href'=>'');
function store_file($filename, &$parent){
    if(empty($filename)) return;
    $matches = array();
    if(preg_match('|^([^/]+)/(.*)$|', $filename, $matches)){
        $nextdir = $matches[1];
        if(!isset($parent['children'][$nextdir])){
            $parent['children'][$nextdir] = array('name' => $nextdir,
                'children' => array(),
                'href' => $parent['href'] . '/' . $nextdir);
        }
        store_file($matches[2], $parent['children'][$nextdir]);
    } else {
        $parent['children'][$filename] = array('name' => $filename,
            'size' => '...', 
            'href' => $parent['href'] . '/' . $filename);
    }
}
foreach($files as $file){
    store_file($file, $root);
}

现在,root['children']的每个元素都是一个关联数组,它散列有关文件或其自己的children数组的信息。