如何通过PHP从API响应的无键数组中调用值?
如何读取无键(索引)数组中的值
首先要明确:你拿到的API响应是JSON格式字符串,第一步必须先把它解析成PHP可操作的对象或数组,才能读取其中的索引数组值。
1. 先修正并解析JSON响应
你给出的API响应里,KFL缺少引号,属于不合法JSON,先修正为合法格式:
*****server: Apache {"success":true,"response":[30,"0.00026508","KFL"]}
在PHP中,使用json_decode()函数把JSON字符串转为对象或关联数组:
// 提取并保留纯JSON部分(去掉前面的server标识文本) $api_json = '{"success":true,"response":[30,"0.00026508","KFL"]}'; // 方式1:转为PHP对象 $data = json_decode($api_json); // 方式2:转为关联数组(第二个参数传true) // $data = json_decode($api_json, true);
2. 读取索引数组的具体值
response字段对应的就是你要的无键索引数组,PHP中索引数组从0开始计数:
若转为对象格式:
// 读取第一个值30 $first_val = $data->response[0]; // 读取第二个值0.00026508 $second_val = $data->response[1]; // 读取第三个值KFL $third_val = $data->response[2]; // 示例判断逻辑 if ($data->response[0] == $var->var_value) { // 执行你的业务代码 }
若转为关联数组格式:
// 读取第一个值30 $first_val = $data['response'][0]; // 读取第二个值0.00026508 $second_val = $data['response'][1]; // 读取第三个值KFL $third_val = $data['response'][2]; // 示例判断逻辑 if ($data['response'][0] == $var->var_value) { // 执行你的业务代码 }
你之前代码的问题
你写的$ar = array($response);是把$response作为单个元素塞进了新数组,此时$ar只有索引0的元素,自然找不到索引1,这就是报错Undefined array key 1的原因。正确逻辑是先解析JSON,再直接访问response下的索引元素。
内容的提问来源于stack exchange,提问作者Kyle McQueen
相关产品推荐
相关产品推荐

