douxie2023 2014-05-21 17:10
浏览 39
已采纳

foreach错误试图获取非对象的属性

here is the nutrionix json ouput

  <?php 
    $json = '{
        "total": 3,
        "max_score": 2.2296956,
        "hits": [
            {
                "_index": "9fa412b9-1dbc-4e35-be7a-0c0c9c8c8e16",
                "_type": "item",
                "_id": "51c3d2b297c3e6d8d3b51ecf",
                "_score": 2.2296956,
                "fields": {
                    "nf_calories": 170,
                    "item_name": "Laksa Paste"
                }
            },
            {
                "_index": "9fa412b9-1dbc-4e35-be7a-0c0c9c8c8e16",
                "_type": "item",
                "_id": "51c35fb297c3e69de4b01eee",
                "_score": 1.3439745,
                "fields": {
                    "nf_calories": 90,
                    "item_name": "Laksa Coconut Curry, Family Size, Medium"
                }
            },
            {
                "_index": "9fa412b9-1dbc-4e35-be7a-0c0c9c8c8e16",
                "_type": "item",
                "_id": "51c3610597c3e69de4b0275d",
                "_score": 1.1046534,
                "fields": {
                    "nf_calories": 40,
                    "item_name": "Spice Paste For Noodles, Laksa, Coconut Curry Noodles, Mild"
                }
            }
        ]
    }';

The i decode $json using json_decode and tried to get nf_calories

$data= json_decode($json);

foreach ($data -> hits as $hit){
    foreach($hit-> fields as $field){
        echo $field->nf_calories;


}

}
?>

the error:

Notice: Trying to get property of non-object in C:\wamp\www\simple_light\testing.php on line 51

when i tried to echo $field;

here is the value

170Laksa Paste90Laksa Coconut Curry, Family Size, Medium40Spice Paste For Noodles, Laksa, Coconut Curry Noodles, Mild

i dont know where i do wrong.

  • 写回答

1条回答 默认 最新

  • douqin231881 2014-05-21 17:16
    关注

    For that structure, in order to get calorie count of every hit, You just need one loop there

    foreach ($data->hits as $hit){
       echo $hit->fields->nf_calories;
    }
    

    Output

    170
    90
    40
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型