我通过api以json的形式获取一些数据:
响应标题:
200 success
access-control-allow-credentials: true
access-control-allow-headers: accept, origin, x-requested-with, authorization, content-type
access-control-allow-methods: OPTIONS, GET, POST, PUT, DELETE
access-control-allow-origin: *
cache-control: no-store, no-cache, must-revalidate
content-length: 1046
content-type: application/json; charset=utf-8
date: Sun, 25 Jul 2021 14:14:51 GMT
expires: Thu, 19 Nov 1981 08:52:00 GMT
pragma: no-cache
server: nginx
x-vendon-api-requests: 2
答复数据:
{
"code": 200,
"result": {
"id": 3075531,
"stock_id": 184445,
"stock_article": "Parfum 2 ml 047 women",
"selections": [
{
"selection": 11,
"label": "11",
"price": 1,
"pricelist": null,
"pricelist_type": null,
"payment_device_type": null
}
],
"type": "PRODUCT",
"name": "Parfum 2 ml 047 women",
"units": null,
"amount": 10,
"amount_max": 11,
"amount_standart": 11,
"amount_critical": 3,
"refill_unit_size": 1,
"min_refill": 1,
"refillable": true,
"last_purchase": 1624011420,
"currency": "EUR",
"recipe": [],
"ingredient_line": null,
"critical": false,
"extraction_time_enabled": null,
"min_extraction_time": null,
"max_extraction_time": null,
"product_price_group": null,
"has_route_planing_expiry_date": false
}
}
然后解码和做 foreach()
要仅输出我需要的变量,请执行以下操作:
代码
$decodedJson = json_decode($html, true);
foreach($decodedJson as $answer) {
echo 'Item:' .$answer['name'].' available '.$answer['amount'].'pcs.';
}
但我被卡住了,因为在输出中得到了重复项(echo行没有变量,而echo行有变量,无法解决这个问题,有人能帮忙吗?
输出
Item: available pcs.Item:Parfum 2 ml 047 women available 10pcs.
1条答案
按热度按时间ycl3bljg1#
您显示的json响应数据不是对象数组,它只是单个对象数据。
因此,不需要循环,只需按照以下操作: