簡體   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