]> 91.132.146.200 Git - dolphin.git/commitdiff
an example of paths to array and json
authorBanana <mail@bananas-playground.net>
Mon, 3 Jan 2022 09:50:16 +0000 (10:50 +0100)
committerBanana <mail@bananas-playground.net>
Mon, 3 Jan 2022 09:50:16 +0000 (10:50 +0100)
single-functions/paths-to-assoc-array.php [new file with mode: 0644]

diff --git a/single-functions/paths-to-assoc-array.php b/single-functions/paths-to-assoc-array.php
new file mode 100644 (file)
index 0000000..ac0702e
--- /dev/null
@@ -0,0 +1,59 @@
+<?php
+/**
+ * dolphin. Collection of useful PHP skeletons.
+ * Copyright (C) 2022  Johannes 'Banana' Keßler
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the COMMON DEVELOPMENT AND DISTRIBUTION LICENSE
+ *
+ * You should have received a copy of the
+ * COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0
+ * along with this program.  If not, see http://www.sun.com/cddl/cddl.html
+ */
+
+/**
+ * out.txt: lines of a unix directory like structure
+ * out.json: The json of the $out array
+ */
+
+
+$out = array();
+$_w = &$out;
+
+$handle = fopen("paths.txt", "r");
+$count = 0; // debug only
+if ($handle) {
+    while (($line = fgets($handle)) !== false) {
+        $_t = explode("/", $line);
+        
+        foreach ($_t as $value) {
+               $value = trim($value);
+            if(empty($value)) continue;
+
+            if(!isset($_w[$value])) {
+                $_w[$value] = array("name" => $value, "children" => array());
+                $_w = &$_w[$value]["children"];
+            }
+            else {
+                $_w = &$_w[$value]["children"];
+            }
+        }
+
+        $_w = &$out;
+
+        /*
+        $count++;
+        if($count > 10) {
+               var_dump($out);
+               exit();
+        }
+        */
+    }
+    fclose($handle);
+} else {
+    // error opening the file.
+    echo "error opening the file";
+} 
+
+//var_dump($out);
+file_put_contents("out.json", json_encode($out, JSON_PRETTY_PRINT));