【发布时间】:2021-09-09 19:13:30
【问题描述】:
我正在通过 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.';
}
但我卡住了,因为输出中出现重复项(没有变量的回声行,而不是有变量的回声行,无法解决这个问题,有人可以帮忙吗?
输出
Item: available pcs.Item:Parfum 2 ml 047 women available 10pcs.
【问题讨论】:
-
$answer = $decodedJson['result'];并删除循环。 “空”输出是因为您将"code": 200,视为实际答案。 -
@Niet the Dark Absol 谢谢
-
您尝试过什么来解决问题?你被困在哪里了?