如何通过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
相关产品推荐
相关产品推荐

