fork download
  1. <?php
  2.  
  3. $paths = [
  4. 'www/webs/apps/pics',
  5. 'www/webs/test',
  6. ];
  7.  
  8. $finalArray = [];
  9. foreach($paths as $path){
  10. $revArr = array_reverse(explode("/", $path)); // This is the trick. Start from build inside out.
  11. $pathArray = [];
  12. foreach($revArr as $key){
  13. $tempBucket = $pathArray;
  14. $pathArray = []; // Create fresh empty array to hold the
  15. $pathArray[$key] = $tempBucket;
  16. }
  17.  
  18. $finalArray = array_merge_recursive($pathArray, $finalArray); // Recursively Merge the array into the main array
  19. }
  20.  
  21. echo "<pre>";
  22. print_r(json_encode($finalArray, JSON_PRETTY_PRINT));
  23. echo "</pre>";
  24.  
Success #stdin #stdout 0.04s 24180KB
stdin
Standard input is empty
stdout
<pre>{
    "www": {
        "webs": {
            "test": [],
            "apps": {
                "pics": []
            }
        }
    }
}</pre>