Getting data from complicated variable

Hello.
I have complicated variable I Got from API by JSON, and I need to extract the “street”.
In this case - “*** I NEED TO GET THIS VALUE ***”
I have variable $data, that stores the following:

string(444) "{
"category":"Concert venue","category_list":[{
"id":"191478144212980","name":"Night Club"}
,{"id":"215343825145859","name":"Social Club"}]
,"location":{
"street":"*** I NEED TO GET THIS VALUE ***",
"city":"some city`",
"state":"",
"country":"some country","zip":"84101","latitude":31.221888491009,"longitude":34.802303128921},"name":"some name","id":"355358751735"}"

I have bolded the value I need to get. I tried for few hours and couldn’t get how to do this.
Is it even possible?

Try this:

$data = json_decode($data, true);
$street = $data['street'];

Manual page for json_decode() function might help a bit too.

The street field is nested inside the location object, so you’d need to do:

$street = $data['location']['street'];
1 Like

Good spot @fretburner :thumbsup:

Warning: Illegal string offset ‘location’ in …
Warning: Illegal string offset ‘street’ in …

Did you inspect the $data variable after passing it through the json_decode() function?

var_dump($data);

When I do it, I get this result

array(5) {
  ["category"]=>
  string(13) "Concert venue"
  ["category_list"]=>
  array(2) {
    [0]=>
    array(2) {
      ["id"]=>
      string(15) "191478144212980"
      ["name"]=>
      string(10) "Night Club"
    }
    [1]=>
    array(2) {
      ["id"]=>
      string(15) "215343825145859"
      ["name"]=>
      string(11) "Social Club"
    }
  }
  ["location"]=>
  array(7) {
    ["street"]=>
    string(32) "*** I NEED TO GET THIS VALUE ***"
    ["city"]=>
    string(10) "some city`"
    ["state"]=>
    string(0) ""
    ["country"]=>
    string(12) "some country"
    ["zip"]=>
    string(5) "84101"
    ["latitude"]=>
    float(31.221888491009)
    ["longitude"]=>
    float(34.802303128921)
  }
  ["name"]=>
  string(9) "some name"
  ["id"]=>
  string(12) "355358751735"
}

You should be getting the same as this above, since it’s derived from the json that you posted originally.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.