json_encode() on a multidimensional array - with string keys
A JSON array has no explicit indexes, it's just an ordered list. The only JSON data structure that has named keys is an object. The literal should make this quite obvious:
["foo", "bar", "baz"]
This array has no named indices and there isn't any provision to add any.
PHP conflates both lists and key-value stores into one array
data type. JSON doesn't.
This is your object:
$parent=new StdClass();$parent->ID=101;$parent->ParentID=0;$parent->Name='Root One';$child1=new StdClass();$child1->ID=1011;$child1->ParentID=$parent->ID;$child1->Name='Child One';$parent->Children[]=$child1;$child1_1=new StdClass();$child1_1->ID=10111;$child1_1->ParentID=$child1->ID;$child1_1->Name='Child One One';$child1->Children[]=$child1_1;
This is your JSON convert function:
echo json_encode($parent,JSON_PRETTY_PRINT);
and this is your object coded into JSON format:
{ "ID": 101, "ParentID": 0, "Name": "Root One", "Children": [ { "ID": 1011, "ParentID": 101, "Name": "Child One", "Children": [ { "ID": 10111, "ParentID": 1011, "Name": "Child One One" } ] } ]}
The answer came later because I started learning PHP later. Anyway, some day, someone might find it useful.
I have now got a working solution which is fast and works well.
Firstly, as written in SO link from the question;
In JSON, arrays only have numeric keys, whereas objects have string properties. The inclusion of a array key forces the entire outer structure to be an object by necessity.
In JSON; Curly braces hold objects (
{}
), Square brackets hold arrays ([]
).So using a string as a key will result in the
json_encode
function returning objects, whereas reseting the keys will ensure it creates arrays.Therefore, just before I return my JSON encoded string, I run a function to reset all the array keys. The code I found on this SO thread (Reset array keys in multidimensional array) was particularly useful!