本文介绍了使用PHP将目录结构(字符串)解析为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像这样的文件路径字符串数组
I have an array of file-path strings like this
- 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
- 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
最终目标是使它们进入jsTree.我从上面的示例字符串中构建了一个原型树.检查一下: http://jsfiddle.net/ecropolis/pAqas/
End goal is to get them to jsTree. I built a prototype tree from the above sample strings.check it out: http://jsfiddle.net/ecropolis/pAqas/
推荐答案
我能够使用这种出色的解决方案(@Casablanca发布的最底层的解决方案)将上述字符串处理为递归数组结构.将路径数组转换为UL列表
I was able to use this excellent solution (the bottom one posted by @Casablanca) to process the above strings into a recursive array structure.Convert array of paths into UL list
<?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 '] }';
?>
这篇关于使用PHP将目录结构(字符串)解析为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!