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

PHP中提取JSON数据payment_method字段值失败如何处理?

正确实现代码

直接替换你foreach中的逻辑即可:

public function prepareDataSource(array $dataSource){
    if (isset($dataSource['data']['items'])) {
        foreach ($dataSource['data']['items'] as & $item) {
            // 校验存储JSON的字段是否存在且为合法字符串
            if (!isset($item['additional_information']) || !is_string($item['additional_information'])) {
                continue;
            }
            // 解码JSON为关联数组
            $infoData = json_decode($item['additional_information'], true);
            // 校验JSON解码成功+目标字段存在
            if (json_last_error() !== JSON_ERROR_NONE || !isset($infoData['payment_method'])) {
                continue;
            }
            // 拿到目标值,可根据需求赋值到item中供后续使用
            $paymentMethod = $infoData['payment_method'];
            $item['payment_method'] = $paymentMethod;
        }
        // 取消引用,避免后续意外修改数组数据
        unset($item);
    }
    return $dataSource;
}

逻辑说明

  • 你之前报错的核心原因是给json_decode传入了数组类型的$item,而json_decode只接受JSON格式字符串作为入参。你已经确认JSON字符串存在$item['additional_information']字段中,直接取这个字段传入解码即可。
  • 解码时传入第二个参数true,会返回关联数组而非对象,方便直接通过键名读取payment_method取值。
  • 代码中增加了多重校验逻辑,避免JSON格式异常、字段缺失时抛出PHP警告。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 19:27:02