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

WooCommerce REST API获取商品详情数组为空及foreach报错求解

WooCommerce REST API 传参异常修复方案

核心问题:你在 single_product.php 中发起接口请求时未携带商品ID参数,导致下游接口拿不到查询条件,返回空数据/非数组格式,json_decode 后得到的内容不是可遍历结构,触发foreach报错。

修复步骤

    1. 修正 single_product.php 的请求逻辑,拼接商品ID参数
<?php  
// 先接收表单提交的商品ID,做合法性校验
$product_id = isset($_GET['edit']) ? intval($_GET['edit']) : 0;
if ($product_id <= 0) {
    die('商品ID无效');
}
// 请求下游接口时拼接GET参数
$api_url = 'http://localhost/api-woocommerce/single_product_connect.php?edit=' . $product_id;
$data = file_get_contents($api_url);
$data = json_decode($data, true);
// 提前校验数据格式,避免foreach报错
if (!is_array($data)) {
    die('商品数据查询失败');
}
?>
    1. 修正 single_product_connect.php 的参数校验和接口调用逻辑
      原代码中调用WooCommerce接口时传入了未定义的$data变量,同时缺少参数校验,调整后代码:
<?php
// 此处保留你原来初始化$woocommerce实例的代码
$product_id = isset($_GET['edit']) ? intval($_GET['edit']) : 0;
if ($product_id <= 0) {
    echo json_encode([]);
    exit;
}
// 查询单个商品接口不需要额外传$data参数
echo json_encode($woocommerce->get("products/{$product_id}"));
?>
    1. 修正页面遍历输出逻辑
      WooCommerce查询单个商品返回的是一维数组,不需要用foreach遍历,直接输出对应字段即可:
<?= $data['id']; ?>
<?= $data['name']; ?>

补充说明

你手动拼接参数访问single_product_connect.php能正常返回,就是因为手动请求时携带了edit参数,代码中请求时没有传参才导致返回空数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 15:36:02