You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让PHP循环仅遍历JSON中的文章数量而非键值对

解决方案

情况1:仅处理单篇文章(当前JSON结构)

如果你的输入始终是单篇文章的JSON,完全不需要foreach循环,直接读取对应字段即可:

$data = json_decode(file_get_contents('php://input'), true);

if (isset($data) && json_last_error() === JSON_ERROR_NONE) {
    $articlenumber = $data['Artikelnr'];
    $voorraad_nl = $data['Vooraad_NL'];
    $voorraad_de = $data['Voorraad_DE'];
    $voorraad_be = $data['Vooraad_BE'];
    // 执行你的业务逻辑,如数据入库、计算等
}

情况2:支持多篇文章(调整JSON结构)

如果需要处理多篇文章,首先要把JSON改成数组包裹多对象的格式,示例如下:

[
  {
    "Artikelnr":"1000",
    "Vooraad_NL":2.0,
    "Voorraad_DE":1.0,
    "Voorraad_BE":0.0
  },
  {
    "Artikelnr":"1001",
    "Vooraad_NL":5.0,
    "Voorraad_DE":3.0,
    "Voorraad_BE":1.0
  }
]

然后PHP代码遍历这个数组,每次循环对应一篇文章:

$data = json_decode(file_get_contents('php://input'), true);

if (isset($data) && is_array($data) && json_last_error() === JSON_ERROR_NONE) {
    foreach ($data as $article) {
        $articlenumber = $article['Artikelnr'];
        $voorraad_nl = $article['Vooraad_NL'];
        $voorraad_de = $article['Voorraad_DE'];
        $voorraad_be = $article['Voorraad_BE'];
        // 处理单篇文章的业务逻辑
    }
}

内容的提问来源于stack exchange,提问作者Matthijs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 13:03:16