Codeigniter PHP Ajax仅返回数组括号

时间:2017-09-28 15:34:52

标签: javascript php arrays ajax codeigniter

我有一个函数返回一个结构如下的数组

[[{"title":"Mr","first_name":"James","last_name":"Loo","date_of_birth":36356,"email":"test@test.com","phone_number":1234567890,"company":"CompanyOne"},{"title":"Mr","first_name":"Jonah","last_name":"Lee","date_of_birth":42629,"email":"test@test2.com","phone_number":1234567890,"company":"CompanyTwo"}],
[]]

阵列中有2个阵列。第一个是“entry not inserted”数组,第二个是“entry inserted”数组。

但是当我通过这个函数执行代码时

$result = $this->curl->execute();
$result_errors = array();
for($j=0;$j<sizeof($result);$j++){
   $result_errors = $result[0];
}
if(sizeof($result_errors)>0){
   echo json_encode($result_errors);
}

我在控制台中获得的结果仅为“[”。

我错过了什么吗?我已经读过我必须回显和json编码数组但它似乎没有出来。

2 个答案:

答案 0 :(得分:0)

如果$result字面意思与上面打印的一样,那么它不是PHP数组,只是JSON格式的字符串。在解码之前,PHP无法解释它。您的for循环是浪费时间,因为您始终将$result的第一个索引分配给$result_errors变量。在PHP中,如果您尝试获取字符串的索引,则只需获取字符串中该位置的字符。 $result的第一个字符是“[”。

如果你试图从响应中获取第一个数组,你需要将JSON解码为PHP数组,选择第一个内部数组,然后将其重新编码回JSON以进行输出,如下所示:

$array = json_decode($result);
echo json_encode($array[0]);

这将为您提供包含两个对象的第一个数组。如果这不是您所追求的输出,那么请澄清。

答案 1 :(得分:0)

我不确定你会得到你想要的但问题是$result_errors的作业。该var应该是一个数组,但是当您进行赋值$result_errors = $result[0];时,您将其从数组更改为$result[0]处的任何值;试试这个

for($j=0;$j<sizeof($result);$j++){
   $result_errors[] = $result[0];
}

我的问题是:由于$ result显然是一个数组(如使用$result[0]所示),为什么不简单地这样做呢?

echo json_encode($result);

建议:而不是sizeof使用count

if(count($result_errors) > 0)
{
   echo json_encode($result_errors);
}

count不太可能被别人误解。它在其他编程语言中具有完全不同的含义。

哦,@ ADyson的回答是正确的,指出需要将json字符串解码为PHP数组。