C0ft C0ft - 4 months ago 19
PHP Question

JSON foreach only gets first result out of an array

I have a JSON file (test.json) which is

{
"fruit": [{
"id": 364823,
"name": "Lemon",
"amount": [33],
"profile": "http://google.com",
"buyid": 5
}, {
"id": 367851,
"name": "Orange",
"amount": [69, 95, 166],
"profile": "http://google.com",
"buyid": 3
},{
"id": 35647,
"name": "Apple",
"amount": [77, 43],
"profile": "http://google.com",
"buyid": 31
} ]
}


then i have my PHP script to echo

$url="test.json";
$json = file_get_contents($url);
$json = json_decode($json, true);
$names = array();
foreach($json['fruit'][0]['amount'] as $val)
{
echo $val . " <br> ";
}


Which returns

33


how can i get it to return?

33
69 95 166
77 43


i can get it to work with the others like id,profile and buyid but not this array

Answer
foreach($json['fruit'] as $fruit){
    echo implode(' ',$fruit['amount']);
}

Live demo

Comments