繁体   English   中英

如何从平面数组制作树-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';

这就是我想要实现的

http://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数组的信息。

暂无
暂无

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

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