0

For the purpose of my website, I need to dynamically produce object keys for my JSON tree structure, at runtime. My structure is nested, with each parent node containing an array of child nodes. This nested structure makes things quite complicated, and can make the key very long as the tree gets deeper. I cannot change this however, as it is needed for the tree drawing plug in that I'm using.

This is the sort of thing im looking for:

$tree->rootNode->{$varString}->title;

where $tree is the JSON and $varString can contain a single element (e.g. children[0]) all the way up to a longer path (e.g. children[0]->children[1]->children[1]). When I hardcode these keys in, everything works fine, but this wouldnt allow me to generate keys at runtime.

The problem seems to be due to the use of a string to store the key. I can use a variable to store a single object name, but not the index [0] or a path of multiple objects using the -> operator.

Is there a way of doing this, or will I have to take an entirely different approach?

  • That does not look like a properly designed structure.... why don't you use objects instead? – Nico Haase Apr 23 '18 at 11:04
  • I have an external Json file containing the structure which is fetched and then stored in the $tree. I can't change the structure, as this is needed for a tree drawing plug in I'm using. My problem is that I need to add new information to this structure at runtime, and I need to be able to generate the appropriate key to do this. I'm able to make the correct path depending on the users actions and store this in the variable $varString, but I can't use this variable to construct a key. I will edit my question to make this clearer. – Heather Lumby Apr 23 '18 at 11:20
  • Read the duplicate. You need to recursively iterate your tree key by key. `->{$varString}` means you're trying to access a key called `"children[0]->children[1]->children[1]"`, which I doubt is the correct key name. – deceze Apr 23 '18 at 11:32
  • I understand that the key looks dodgy, but that is the actual structure. When hard coding this key in, everything works fine. My problem is just using a string as part of a key. I could look into iterating through my tree, but I only want to resort to this if i really cant use a string as part of my key. – Heather Lumby Apr 23 '18 at 11:40
  • Any `foo->$bar` will always mean that it will look for the key `$bar` on the object `foo`. It will never evaluate whether `$bar` might look like a PHP nested object access notation syntax and expand that into `foo->$bar[0]->$bar[1]->$bar[2]->...`. That's not how it works. Read. The. Duplicate. – deceze Apr 23 '18 at 11:42
  • Ok thank you. All I wanted to know is if it was possible or not. – Heather Lumby Apr 23 '18 at 11:46

0 Answers0