Parse Directory Structure (Strings) to JSON using PHP

元气小坏坏 提交于 2019-12-21 09:14:57

问题


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

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/


回答1:


Firstly I would create a recursive function to iterate through your directory into an array

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

and then output the array with json_encode.

Source used from: http://www.php.net/manual/en/function.readdir.php#87733




回答2:


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 '] }';
?> 



回答3:


I fixed the concatenation answer chosen by @Ecropolis to use arrays. His initial example helped me, but I agree with @RobertPitt that i needs a json_encode to really be properly a good solution.

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


来源:https://stackoverflow.com/questions/4987551/parse-directory-structure-strings-to-json-using-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!