It feels like a question which has already been asked but I have not been able to find an answer to this.
Say I have a JSON file like this:
{
"material": {
"name": "material",
"nav": [
{
"text": "Backgrounds",
"url": "backgrounds"
},
{
"text": "Templates",
"url": "templates"
}
],
"methods": [{
"index":[{
"title": "Material",
"description": "Bla",
"keywords": [ "website material", "sozai", "素材" ]
}],
"backgrounds":[{
"title": "Backgrounds",
"description": "Bla.",
"keywords": [ "website backgrounds", "tiled backgrounds"]
}]
}]
}
}
And I json_decode it
$pages = json_decode($data);
To access, say, material > methods > index > title, I could do
$pages->material->methods[0]->index[0]->title
And that is fine (or is it?)
But this would not work with variables mixed in. Elsewhere I get the method name ($method, which will be "index") and put it in place of index.
$pages->material->methods[0]->$method[0]->title
This results in a "Undefined property: stdClass::$i"
I am aware that I can break this problem up into more lines storing the array in a new variable then indexing from there, but that is what I am trying to find the alternative to.
I would like to know if there is a more intuitive way to index this (without the [0]?) without going outside that one expression.
$pages->material->methods[0]->{$method}[0]->title?trueto the second parameter ofjson_decode()to force it to be an associative array. Then you can use your variable, eg$pages['material']['methods'][0][$method][0]['title']