0

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!

fhollste
  • 785
  • 6
  • 16
  • You probably need to parse your string and loop over the components. Or use something like `eval`... – jeroen Feb 24 '15 at 13:03

2 Answers2

0

It seems that you have json data with you..you can use below code..

$obj= json_decode($yourJsonData);
print_r($obj);

foreach ($obj as $key => $value) { 
    $companyinfo = $value['companyInfo']['companyName'];
}

In foreach loop you will get require key and values..this is just a example for you..

Prashant M Bhavsar
  • 1,136
  • 9
  • 13
0

Why do you exactly need this?

All you have to do is:

$jsonData = json_decode($jsonString, true);

echo $jsonData['adverts'][0]['companyInfo']['companyName'];

//or

foreach($jsonData['adverts'] as $advert){
    echo $advert['companyInfo']['companyName'];
}
Carlos
  • 53
  • 5
  • Yes but the property names and object "depth" is not known, thus the need for variables. – fhollste Feb 24 '15 at 13:01
  • 1
    @Holle take a look here: http://stackoverflow.com/questions/1019076/how-to-search-by-key-value-in-a-multidimensional-array-in-php – Carlos Feb 24 '15 at 13:06
  • Thanks @Carlos! I read that answer but I was hoping for a simpler solution which doesn't involve looping/searching since I "just" need to somehow make this: $item->"companyInfo->companyName" into this $item->companyInfo->companyName – fhollste Feb 24 '15 at 13:18
  • It will require you to do a search loop, even if you're working whith objects, since your json is structured as "various companies". If you dont want it, you'll have to assume its aways looking in the first row (index 0 for example) – Carlos Feb 24 '15 at 13:27
  • I updated my question with a priliminary solution with looping. Thanks – fhollste Feb 24 '15 at 13:55