JSON foreach只从数组中获取第一个结果

时间:2016-07-25 02:06:57

标签: php json

我有一个JSON文件(test.json),它是

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

然后我有我的PHP脚本回应

$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> ";
}

返回

33

我怎么能让它回来?

33
69 95 166
77 43

我可以让它与其他人合作,例如 id 个人资料 buyid ,但不是这个数组

1 个答案:

答案 0 :(得分:3)

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

Live demo

相关问题