Parse Directory Structure (Strings) to JSON using PHP

phpjsonparsedecodeencodeusingstringsstructuredirectory

Last Update : 2023-09-22 UTC 09:31:05 AM

Answers of > Parse Directory Structure (Strings) to JSON using PHP

I was able to use this excellent solution w3coded php decode (the bottom one posted by @Casablanca) to w3coded php decode process the above strings into a recursive array w3coded php decode structure. Convert array of paths into UL list, w3coded php decode w3coded php decode Stack Overflow for Teams w3coded php decode Where developers & technologists share w3coded php decode private knowledge with coworkers w3coded php decode , w3coded php decode w3coded php decode @RobertPitt w3coded php decode Trying to achieve similar result with w3coded php decode RecursiveIterator. Thanks for any help in w3coded php decode stackoverflow.com/questions/24121723/… w3coded php decode – YahyaE w3coded php decode Jun 9 '14 at 20:22 w3coded php decode , w3coded php decode w3coded php decode I have the filenames above as w3coded php decode strings in an array. Since I'm not reading an w3coded php decode actual directory with PHP I don't have access to w3coded php decode functions like is_file maybe that's all I really w3coded php decode need to get around. In my case if I split on '/' w3coded php decode the file is the last element of the exploded w3coded php decode string to array. (The file strings are coming w3coded php decode from a query to Amazon S3) w3coded php decode – Ecropolis w3coded php decode Feb 14 '11 at 0:42 w3coded php decode

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

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

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

Current topics : Parse Directory Structure (Strings) to JSON using PHP

Newly Added Questions

Similar Questions

Questions :

How To Group Array Key Value

Last Update : 2023-09-22 UTC 13:00:19 PM

Questions :

PhpStorm Warning For React Attributes In Jsx File With SCSS File

Last Update : 2023-09-22 UTC 13:00:01 PM

Questions :

Why Is The File Not Showing Up In Request.files And In Request.forms Instead?

Last Update : 2023-09-22 UTC 12:59:56 PM

Questions :

Proxying Assets From React App Directory In Slim Framework?

Last Update : 2023-09-22 UTC 12:59:44 PM

Questions :

Laravel 5.4 Can't Run “php Artisan Preset React” Comand

Last Update : 2023-09-22 UTC 12:59:31 PM

Questions :

How To Update Session Values Without Signing Out?

Last Update : 2023-09-22 UTC 12:59:25 PM

Questions :

Array Is Not Visible

Last Update : 2023-09-22 UTC 12:59:16 PM

Questions :

React Routing For Login Using Symfony

Last Update : 2023-09-22 UTC 12:58:59 PM

Questions :

Sanctum With React SPA Returning 419 Page Expired

Last Update : 2023-09-22 UTC 12:58:48 PM

Questions :

How Do I Import An Input String Into Another Page

Last Update : 2023-09-22 UTC 12:58:30 PM

Top
© 2023 W3CODED - All Rights Reserved.