繁体   English   中英

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

[英]Parse Directory Structure (Strings) to JSON using PHP

我有一个像这样的文件路径字符串数组

  • 视频/滑稽/ jelloman.wmv
  • 视频/滑稽/ bellydance.flv
  • 视频/ abc.mp4
  • 视频/ june.mp4
  • 视频/ cleaver.mp4
  • 音频/ uptown.mp3
  • 音频/ juicy.mp3
  • fun.wmv
  • jimmy.wmv
  • herman.wmv

最终目标是让他们到jsTree。 我从上面的示例字符串构建了一个原型树。 看看: http//jsfiddle.net/ecropolis/pAqas/

首先,我将创建一个递归函数,将您的目录迭代到一个数组中

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;    
}

然后使用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 '] }';
?> 

我修复了@Ecropolis选择的连接答案来使用数组。 他最初的例子帮助了我,但我同意@RobertPitt我需要一个json_encode才能真正成为一个好的解决方案。

  $filesArray = 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');
  $finalTree = $this->parseArrayToTree($filesArray);

  $finalJsonTree = json_encode($finalTree);

  function parseArrayToTree($paths) {
    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
      }
    }

    $dataArray = array();
    $dataArray['data'] = array();
    $dataArray['data'] = $this->buildUL($array, '');
    return $dataArray;
  }

  function buildUL($array, $prefix) {
    $finalArray = array();

    foreach ($array as $key => $value)
    {
      $levelArray = array();
      $path_parts = pathinfo($key);
      if (!empty($path_parts['extension']) && $path_parts['extension'] != '')
      {
        $extension = $path_parts['extension'];
      }
      else
      {
        if (empty($value))
        {
          $extension = "";
        }
        else if (is_array($value))
        {
          $extension = 'folder';
        }
      }

      if (is_array($value))
      { //its a folder
        $levelArray['data'] = $key;
      }
      else
      { //its a file
        $levelArray['data']['title'] = $key;
        $levelArray['attr']['href'] = $prefix . $key;
        $levelArray['attr']['id'] = $prefix . $key;
        $levelArray['icon'] = "images/" . $extension . "-icon.gif";
      }

      // if the value is another array, recursively build the list$key
      if (is_array($value))
      {
        $levelArray['children'] = $this->buildUL($value, $prefix . $key . "/");
      }

      $finalArray[] = $levelArray;
    } //end foreach

    return $finalArray;
  }

暂无
暂无

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

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