0

Sorry if this is rookie standard. The nesting really confuses me. Code here:

$json= '[{ "all":
 "{"data":
 [ {"name": "Kofi", "age":13}, {"name": "Jay", "age":17} ]
}"
}]' ;

$decode = json_decode($json);
$names= $decode->all->data->name;

// I want to retrieve "Kofi" and "Jay"

foreach ($names as $name){
echo $name;
}

I want to retrieve Kofi, Jay I get the error: Trying to get property 'all' of non-object

8
  • 3
    You have an array of one object. That one object has one key, all whose value is a string of JSON data. You need to decode the outer array, then decode the value of the all key. Commented Mar 6, 2019 at 19:41
  • try with $decode[0]->all->data[0]->name; and $decode[0]->all->data[1]->name; Commented Mar 6, 2019 at 20:13
  • Tried that. Didnt work. Same error: trying to get property 'all' of non-object. Thanks though. Commented Mar 6, 2019 at 20:23
  • You want to convert the json to ? a php associative array ? Commented Mar 6, 2019 at 20:30
  • 2
    your json is not correct... is not a valid json Commented Mar 6, 2019 at 20:42

1 Answer 1

1

I ran your json, it wasn't formatted properly. I have formatted it and this extra bit of code should do the job for you.

NOTE: The only difference was "all": "{"...."}" changed to "all": { .... }

    $json= '[
            {
                "all":
                    {
                        "data":
                                [ 
                                    { "name": "Kofi", "age":13}, 
                                    {"name": "Jay", "age":17} 
                                ]
                    }
            }
        ]';

    $decode = json_decode($json);

    foreach($decode[0]->all->data as $dec) {
        echo $dec->name. '<br/>';
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.