1

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

2
  • What are you trying to achieve? What's the expected result? Commented Apr 22, 2014 at 14:09
  • try this: $feature['b']['ba'] Commented Apr 22, 2014 at 14:09

1 Answer 1

1

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"]

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the quick reply! Your insight helped me a great deal!

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.