【问题标题】:Foreach result echo do duplicate row output (in the beginning without variable, then with variable)Foreach 结果回显重复行输出(开始时没有变量,然后是变量)
【发布时间】: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 谢谢
  • 您尝试过什么来解决问题?你被困在哪里了?

标签: php json


【解决方案1】:

您显示的 json 响应数据不是对象数组,它只是单个对象数据。

所以不需要循环,只需执行以下操作:

$answer = json_decode($html, true);
echo 'Item:'.$answer['result']['name'].' available '.$answer['result']['amount'].'pcs.'; 

【讨论】:

    猜你喜欢
    • 2012-09-09
    • 1970-01-01
    • 2017-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多