CURL获取API JSON后无法读取users_type数组元素的问题
解决PHP解析JSON后读取users_type数组元素的问题
核心问题原因
你用json_decode($authToken, true)解析后,返回的是关联数组而非对象,所以不能用对象的->语法访问节点,必须用数组下标['键名']的方式。之前的报错要么是混用了两种访问方式,要么是没逐层确认节点是否存在。
正确写法
先逐层验证节点的存在性,避免触发"Undefined array key"或"访问null值数组偏移"警告,再读取对应元素(注意PHP数组索引从0开始,第1位对应索引0,第2位对应1,第3位对应2):
// 确认所有层级节点存在且为数组 if (isset($responeds['users_info']['data']['users_type']) && is_array($responeds['users_info']['data']['users_type'])) { $users_type = $responeds['users_info']['data']['users_type']; // 读取第1、2、3位元素,用??处理数组长度不足的情况 $item1 = $users_type[0] ?? null; $item2 = $users_type[1] ?? null; $item3 = $users_type[2] ?? null; }
排查小技巧
如果依然有问题,先打印users_info下的data节点结构,确认键名和数组格式:
print_r($responeds['users_info']['data']);
这样能快速排查是不是users_type拼写错误,或者data本身为null/非数组的情况。
内容的提问来源于stack exchange,提问作者Edward Bahnasi
相关产品推荐
相关产品推荐

