如何使用 PHP 从 cURL 中提取
我有一个API,可以以这种格式获得结果:
{1 item
"items":[3 items
0:{12 items
"sugar_g":0
"fiber_g":0
"serving_size_g":396.893
"sodium_mg":246
"name":"prime rib"
"potassium_mg":720
"fat_saturated_g":43.7
"fat_total_g":107.7
"calories":1383.1
"cholesterol_mg":323
"protein_g":88.6
"carbohydrates_total_g":0
}
1:{12 items
"sugar_g":3.6
"fiber_g":2.3
"serving_size_g":100
"sodium_mg":587
"name":"pizza"
"potassium_mg":217
"fat_saturated_g":4.5
"fat_total_g":9.8
"calories":262.9
"cholesterol_mg":16
"protein_g":11.4
"carbohydrates_total_g":32.9
}
2:{12 items
"sugar_g":1.4
"fiber_g":1.5
"serving_size_g":100
"sodium_mg":329
"name":"mashed potatoes"
"potassium_mg":47
"fat_saturated_g":0.7
"fat_total_g":4.2
"calories":114
"cholesterol_mg":0
"protein_g":2
"carbohydrates_total_g":16.8
}
]
}
如何提取此数据,以便可以将它们存储在变量中?
我已经尝试过,但是只给我一个结果,
$jsonDecoded = json_decode($response,true);
foreach($jsonDecoded['items'] as $item){
$sugar = $item['sugar_g'];
$calories = $item['calories'];
$name = $item['name'];
$serving_size = $item['serving_size_g'];
}
我想实现的目标是我可以提取所有糖,卡路里,名称等
I have an API that gives me results in this format:
{1 item
"items":[3 items
0:{12 items
"sugar_g":0
"fiber_g":0
"serving_size_g":396.893
"sodium_mg":246
"name":"prime rib"
"potassium_mg":720
"fat_saturated_g":43.7
"fat_total_g":107.7
"calories":1383.1
"cholesterol_mg":323
"protein_g":88.6
"carbohydrates_total_g":0
}
1:{12 items
"sugar_g":3.6
"fiber_g":2.3
"serving_size_g":100
"sodium_mg":587
"name":"pizza"
"potassium_mg":217
"fat_saturated_g":4.5
"fat_total_g":9.8
"calories":262.9
"cholesterol_mg":16
"protein_g":11.4
"carbohydrates_total_g":32.9
}
2:{12 items
"sugar_g":1.4
"fiber_g":1.5
"serving_size_g":100
"sodium_mg":329
"name":"mashed potatoes"
"potassium_mg":47
"fat_saturated_g":0.7
"fat_total_g":4.2
"calories":114
"cholesterol_mg":0
"protein_g":2
"carbohydrates_total_g":16.8
}
]
}
how can I extract this data so that I can store them in variables?
i have tried this, but give me just one result
$jsonDecoded = json_decode($response,true);
foreach($jsonDecoded['items'] as $item){
$sugar = $item['sugar_g'];
$calories = $item['calories'];
$name = $item['name'];
$serving_size = $item['serving_size_g'];
}
what I'm trying to achieve is I can extract all Sugars, Calories, Name and etc
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您在 json_decode() 函数中传递 true 时,它将是数组,因此您需要作为数组进行访问,并且有多个数据,因此您需要循环。
when you pass true in
json_decode()
function it will be array so you need to access as array and there is a multiple data so you need loop.