且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用PHP将目录结构(字符串)解析为JSON

更新时间:2023-01-17 12:44:16

我能够使用这种出色的解决方案(@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 '] }';
?>