Ruudvddries Ruudvddries - 4 months ago 30
PHP Question

JSON decode sub array

I'm trying to foreach loop with PHP trough a bunch of this kind of JSON code (via a url);

{
"abc": [{
"a": "1",
"b": [{
"ba": 1,
"bb": 2
}],
"c": 3,
"d": [{
"da": 4,
"db": 5
},
{
"dc": 6,
"dd": 7
}],
"e": 8,
"f": 9,
}]


I'm able to get the key values of "a", "c", "e" and "f".

I use this code to do so;

$url = 'http://url.com/json';

$jsondata = file_get_contents($url);

$jso = json_decode($jsondata, TRUE);

$data = $json['abc'];

foreach ($data as $feature)
{
echo $feature['a'];
}


When I try
echo $feature['b']
'Array' is displayed.
$feature['ba']
displays
Undefined index: ba in <b>x:/test.php</b> on line x

Answer

If you loop over $json["abc"][0] the keys will be a, b, c, d, e and f.

$url = 'http://url.com/json';
$jsondata = file_get_contents($url);
$json = json_decode($jsondata, TRUE);

$data = $json['abc'][0];
foreach ($data as $key => $value) {
    var_dump($key, $value);
}

"ba" would be: $json["abc"][0]["b"][0]["ba"]

"dc" would be: $json["abc"][0]["d"][1]["dc"]