I found the following code online. And I would love to use it in my own projects.
http://dbushell.github.io/Nestable/
This draggable jquery generated tree structure generates a serialized array. To for what seems to me this is a serialized javascript array.
[{"id":1,"children":[{"id":3}]},{"id":2,"children":[{"id":4},{"id":9,"children":[{"id":5,"children":[{"id":6},{"id":7},{"id":8}]}]}]},{"id":11},{"id":12,"children":[{"id":10}]}]
For what I could find I should use parse_str and that should do it.
But to no avail. The array generated is empty.
I tried the following test code :
<?php
$Str = '[{"id":1},{"id":2,"children":[{"id":3},{"id":4},{"id":5,"children":[{"id":6},{"id":7},{"id":8}]},{"id":9},{"id":10}]},{"id":11},{"id":12}]';
parse_str($Str, $values);
print_r($values);
?>
I hope that anyone sees what I am overlooking.
Thanks in advance!
Answer!
What I have overlooked is that this is not a Javascript Serialized array but rather a JSON encoded string.
As suggested below I should use JSON decode.
$Str = json_decode('[{"id":1},{"id":2,"children":[{"id":3},{"id":4},{"id":5,"children":[{"id":6},{"id":7},{"id":8}]},{"id":9},{"id":10}]},{"id":11},{"id":12}]');
This will deliver the result as shown below.
IF I want to use the result as an array instead of what supplied I should use the following function to convert the objects to a valid array:
function toArray($obj){ if (is_object($obj)) $obj = (array)$obj; if (is_array($obj)) { $new = array(); foreach ($obj as $key => $val) { $new[$key] = toArray($val); } } else { $new = $obj; } return $new; } $Str = toArray($Str);
(* this I copied from : How do I convert an object to an array? *)