Objectives: I am trying to read certain parts of any json file by letting the user input the desired properties.
Say I have an object that looks like this:
"adverts": [
{
"id": "33655628",
"companyInfo": {
"companyName": "Company A",
"homepage": "http://companya.com",
"companyText": null
},
...
]
I want to access the properties by assigning the property name or "path" by a variable. Accessing the first level ($item->$_id) works fine but how do I access a nested property companyName directly with by a variable such as
$_name = "companyInfo->companyName";
Ex:
$_repeat = "adverts";
$_id = "id";
$_name = ??????
foreach($data->$_repeat as $item){
var_dump($item->$_id);
var_dump($item->$_name);
}
EDIT: As clarification: I want this to be universal for any JSON object!
PRELIMINARY SOLUTION: I got the desired results by looping as suggested by @Carlos:
$_title_a = explode(".",$_title);
$current = $document;
foreach($_title_a as $a){
$current = $current->$a;
}
var_dump($current);
If someone has a better suggestion, I would be glad to hear it. Thanks everybody!