paths-to-assoc-array.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. /**
  3. * dolphin. Collection of useful PHP skeletons.
  4. * Copyright (C) 2022 Johannes 'Banana' Keßler
  5. *
  6. * This program is free software: you can redistribute it and/or modify
  7. * it under the terms of the COMMON DEVELOPMENT AND DISTRIBUTION LICENSE
  8. *
  9. * You should have received a copy of the
  10. * COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0
  11. * along with this program. If not, see http://www.sun.com/cddl/cddl.html
  12. */
  13. /**
  14. * out.txt: lines of a unix directory like structure
  15. * out.json: The json of the $out array
  16. */
  17. $out = array();
  18. $_w = &$out;
  19. $handle = fopen("paths.txt", "r");
  20. $count = 0; // debug only
  21. if ($handle) {
  22. while (($line = fgets($handle)) !== false) {
  23. $_t = explode("/", $line);
  24. foreach ($_t as $value) {
  25. $value = trim($value);
  26. if(empty($value)) continue;
  27. if(!isset($_w[$value])) {
  28. $_w[$value] = array("name" => $value, "children" => array());
  29. $_w = &$_w[$value]["children"];
  30. }
  31. else {
  32. $_w = &$_w[$value]["children"];
  33. }
  34. }
  35. $_w = &$out;
  36. /*
  37. $count++;
  38. if($count > 10) {
  39. var_dump($out);
  40. exit();
  41. }
  42. */
  43. }
  44. fclose($handle);
  45. } else {
  46. // error opening the file.
  47. echo "error opening the file";
  48. }
  49. //var_dump($out);
  50. file_put_contents("out.json", json_encode($out, JSON_PRETTY_PRINT));