我想将数组的数组转换为JSON字符串,但是看来我在项目中使用的方法在特定情况下不起作用。
我有以下代码(不起作用):
$i = 0;
$array = array();
while ($data = $req->fetch()){
$message = array();
$message['id_message'] = intval($data['id']);
$message['id_messaging'] = $data['id_messaging'];
$array[$i] = $message;
$i++;
}
$json = json_encode($array);
print_r($array);
var_dump($array);
print_r($json);
var_dump($json);
return $json;
当我尝试在print_r
或var_dump
上$array
或$json
时,会导致502 Bad Gateway
错误。
我已经测试了几件事:
所有$data['...']
值都已设置(此后的SQL正常工作)
当我仅在$message
中设置一条信息(例如仅$message['id_message'] = intval($data['id']);
)时,json_encode
,print_r
和var_dump
就会起作用在$array
和$json
上正确显示。例如,我得到以下结果:
[{"id_message":203},
{"id_message":201},
{"id_message":199}]
同时,我还有另一段代码以相同的方式获取其他数据:
$i = 0;
while($data = $req->fetch()){
$user = array();
$user['id'] = intval($data['id']);
$user['name'] = $data['name'];
$user['surname'] = $data['surname'];
$user['image'] = $data['image'];
$user['mail'] = $data['mail'];
$arrayUsers[$i] = $user;
$i++;
}
//var_dump($arrayUsers);
//Création de l'adresse
$json = json_encode($arrayUsers);
print_r($json);
return $json;
第二段代码按预期工作。它返回此JSON:
[{"id":106,"name":"n2","surname":"1","image":"1","mail":"miuig"},
{"id":105,"name":"n1","surname":"1","image":"1","mail":"miuig"},
{"id":94,"name":"n2","surname":"1","image":"miohhu","mail":"miuig"}]