这是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
$data= json_decode($json);
foreach ($data -> hits as $hit){
foreach($hit-> fields as $field){
echo $field->nf_calories;
}
}
?>
错误:
注意:尝试获取非对象的属性 第51行的C:\ wamp \ www \ simple_light \ testing.php
当我试图回复$ field时;
这是值
170Laksa Paste90Laksa椰子咖喱,家庭大小,Medium40Spice Paste 面条,Laksa,椰子咖喱面,温和
我不知道我哪里做错了。
答案 0 :(得分:2)
对于那种结构,为了获得每次击中的卡路里计数,你只需要一个循环
foreach ($data->hits as $hit){
echo $hit->fields->nf_calories;
}
<强>输出强>
170
90
40