Curnelious
Curnelious

Reputation: 1

Get array out of a Json?

I am getting a Json respond with :

$response = curl_exec($rest);  
 $json = json_decode($response, true);

I manage to get its values(strings) with :

$foundUserId=$json['results'][0]['userId'];
$foundName=$json['results'][0]['name'];
$foundPhoneNum=$json['results'][0]['phoneNumber'];

But the last value- phoneNumber, is array of strings .

If i try then to loop over it i get nothing(although the array is there in the Json)

  foreach ($foundPhoneNum as &$value) 
    {
      print_r($value);

    }

What am i doing wrong ?

EDIT : The json:

Array ( [results] => Array ( [0] => Array ( [action] => message [createdAt] => 2015-11-21T09:36:33.620Z [deviceId] => E18DDFEC-C3C9 [name] => me [objectId] => klMchCkIDi [phoneNumber] => ["xx665542","xxx9446"] [state] => 1 [updatedAt] => 2015-11-22T08:24:46.948Z [userId] => 433011AC-228A-4931-8700-4D050FA18FC1 ) ) )  

Upvotes: 1

Views: 60

Answers (3)

vl.lapikov
vl.lapikov

Reputation: 796

You might have json as a string inside json. That's why after json_decode() you still have json inside phoneNumber. You have 2 options:

  • Decode phoneNumber like

    $foundPhoneNum=json_decode($json['results'][0]['phoneNumber']);
    
  • Build proper initial json. Instead of

    {"phoneNumber": "[\"xx665542\",\"xxx9446\"]"}
    

    should be

    {"phoneNumber": ["xx665542","xxx9446"]}
    

Upvotes: 2

NoChecksum
NoChecksum

Reputation: 1226

There's a couple of ways to debug situations like this as mentioned in the comments; print_r() and var_dump().

var_dump(), although harder to read the first few times, is my favourite because it tells you the data types of each value in the array. This will confirm whether or not the expected string is indeed an array.

An example from the var_dump() documentation:

<?php
$a = array(1, 2, array("a", "b", "c"));
var_dump($a);

And the output is;

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  array(3) {
    [0]=>
    string(1) "a"
    [1]=>
    string(1) "b"
    [2]=>
    string(1) "c"
  }
}

As you can see it shows array, int and string as the data types.

You might also like to install the Xdebug extension for PHP which dumps more useful error messages and tracebacks. Again harder to read the first few times, but well worth it!

Upvotes: 2

Imran
Imran

Reputation: 4750

foreach ($foundPhoneNum as $value) 
{
      print_r($value);

}

There was an extra & before $value. Try this.

Upvotes: 1

Related Questions