如何使用 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'];
 }

我想要实现的是我可以提取所有的糖、卡路里、名称等

迪利普·帕特尔

当您在json_decode()函数中传递 true 时,它​​将是数组,因此您需要作为数组访问。

 $jsonDecoded = json_decode($response,true);
 foreach(jsonDecoded['items'] as $item){
   echo $item['sugar_g'];
 }
 

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章