如何使用 PHP 从 cURL 中提取

how to extract from cURL using PHP

我有一个 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'];
 }