尝试获取非对象属性的foreach错误 [英] foreach error trying to get property of non-object

查看:85
本文介绍了尝试获取非对象属性的foreach错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是nutrionix json输出

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"
                }
            }
        ]
    }';

我使用json_decode解码$ json并尝试获取nf_calories

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;


}

}
?>

错误:

注意:尝试获取非对象的属性 C:\ wamp \ www \ simple_light \ testing.php,第51行

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

当我试图回显$ field时;

when i tried to echo $field;

这是值

170Laksa Paste90Laksa椰子咖喱,家庭装,中号40香料酱 面条,叻沙,椰子咖喱面,温和的

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

我不知道我在哪里做错了.

i dont know where i do wrong.

推荐答案

对于该结构,为了获取每次点击的卡路里计数,您只需要在其中循环一个

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

输出

170
90
40

这篇关于尝试获取非对象属性的foreach错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆