Search code examples
phplaraveljsondecoder

access to this array data


i have this array result with print_r:

Array
(
    [0] => stdClass Object
        (
            [id] => 
            [place_id] => ChIJ7w0gwihoXz4R4F5KVQWLoH0
            [label] => Address Downtown - Sheikh Mohammed bin Rashid Boulevard - Dubai - United Arab Emirates
            [value] => Address Downtown - Sheikh Mohammed bin Rashid Boulevard - Dubai - United Arab Emirates
            [details] => stdClass Object
                (

but i need to get place_id property, how i can get this?

i´m trying with data[0]->place_id data["place_id"] but always returned me local.ERROR: Illegal string offset 'place_id'

update

if($select == "address"){
                    $aux = $google->getGoogleAddress($select);

                    print_r(json_decode($aux[0]->place_id));
                    /*$this->newData["place_id"] = $aux["place_id"];
                    $google->generateURL($this->newData);*/

SOLUTION

json_decode($aux)[0]->place_id

thanks for help


Solution

  • The error is in the misunderstanding how decoding works. What you're doing:

    json_decode($aux[0]->place_id)
    

    fails because $aux is a string. Which means you're trying to do both array and object property access on it while it's still a string.

    In order to receive an array, the JSON string needs to be fully decoded first:

    $decoded = json_decode($aux);
    

    After that, $decoded is an array of stdClass objects and $decoded[0]->place_id should contain what you need. You can, however, do it in one step (in case you don't have to use any other portions of the data):

    json_decode($aux)[0]->place_id