Ecr*_*lis 9 php json recursive-datastructures
我有一个像这样的文件路径字符串数组
最终目标是让他们到jsTree.我从上面的示例字符串中构建了一个原型树.看看:http://jsfiddle.net/ecropolis/pAqas/
Rob*_*itt 15
首先,我将创建一个递归函数,将您的目录迭代到一个数组中
function ReadFolderDirectory($dir,$listDir= array())
{
$listDir = array();
if($handler = opendir($dir))
{
while (($sub = readdir($handler)) !== FALSE)
{
if ($sub != "." && $sub != ".." && $sub != "Thumb.db")
{
if(is_file($dir."/".$sub))
{
$listDir[] = $sub;
}elseif(is_dir($dir."/".$sub))
{
$listDir[$sub] = $this->ReadFolderDirectory($dir."/".$sub);
}
}
}
closedir($handler);
}
return $listDir;
}
Run Code Online (Sandbox Code Playgroud)
然后输出数组json_encode
.
来源使用自:http://www.php.net/manual/en/function.readdir.php#87733
我能够使用这个优秀的解决方案(@Casablanca 发布的底部解决方案)将上述字符串处理为递归数组结构。 将路径数组转换为 UL 列表
<?php
$paths = array('videos/funny/jelloman.wmv','videos/funny/bellydance.flv','videos/abc.mp4','videos/june.mp4','videos/cleaver.mp4','audio/uptown.mp3','audio/juicy.mp3','fun.wmv', 'jimmy.wmv','herman.wmv');
sort($paths);
$array = array();
foreach ($paths as $path) {
$path = trim($path, '/');
$list = explode('/', $path);
$n = count($list);
$arrayRef = &$array; // start from the root
for ($i = 0; $i < $n; $i++) {
$key = $list[$i];
$arrayRef = &$arrayRef[$key]; // index into the next level
}
}
function buildUL($array, $prefix,$firstrun) {
$c = count($array);
foreach ($array as $key => $value) {
$path_parts = pathinfo($key);
if($path_parts['extension'] != '') {
$extension = $path_parts['extension'];
} else {
$extension = 'folder';
}
if ($prefix == '') { //its a folder
echo ' { "data":"'.$key.'"';
} else { //its a file
echo '{"data" : {"title":"'.$key.'"},"attr":{"href": "'.$prefix.$key.'","id": "1239"},
"icon": "images\/'.$extension.'-icon.gif"';
}
// if the value is another array, recursively build the list$key
if (is_array($value)) {
echo ',"children" : [ ';
buildUL($value, "$prefix$key/",false);
}
echo "}";
$c = $c-1;
if($c != 0) {
echo ",";
}
} //end foreach
if($firstrun != true)
echo "]";
}
echo '{ "data" : [';
buildUL($array, '',true);
echo '] }';
?>
Run Code Online (Sandbox Code Playgroud)