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

如何通过PHP从JSON响应数据中提取discount_percentage字段的值

PHP解析JSON获取discount_percentage字段解决方案

错误原因梳理

  • 调用json_decode($response, true)时第二个参数传入true,返回结果为关联数组,不能使用对象运算符->访问属性
  • 目标JSON中data字段是索引数组,需先定位到数组对应下标元素,才能访问内部的discount_percentage字段
  • 你已经完成了JSON整体解析,不需要重复调用json_decode,$discount_percentage="$arr"的写法也无实际作用

正确实现代码

基础适配(针对你给出的单条data数据结构)

$arr = json_decode($response, true);
// 增加非空判断避免下标不存在报错
if ($arr && $arr['status'] == 'OK' && !empty($arr['data'])) {
    // 取data数组第一个元素的discount_percentage值
    $discount_percentage = $arr['data'][0]['discount_percentage'];
    // 测试输出结果为100
    echo $discount_percentage;
}

扩展适配(data字段包含多条数据时遍历取值)

$arr = json_decode($response, true);
if ($arr && $arr['status'] == 'OK' && !empty($arr['data'])) {
    foreach ($arr['data'] as $item) {
        // 依次输出每个条目的折扣值
        echo $item['discount_percentage'] . PHP_EOL;
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 17:09:04