Php : json_encode 在字符串的开头返回 NULL 数组
Php : json_encode is returning NULL array at the start of the string
这是我的 Php 代码。我是 php 的新人,我想得到 JSON.
的适当回应
$db_handle = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $db_handle )
{
die('Could not connect: ' . mysql_error());
}
else
$response["message"] = "Connected Succsessfully";
//echo json_encode($response);
$db_found = mysql_select_db($db, $db_handle);
// check for required fields
if($db_found)
{
// mysql inserting a new row
mysql_query('SET CHARACTER SET utf8');
$query = "SELECT * FROM users";
$result = mysql_query($query);
//iterate over all the rows
$emparray[] = array();
while($row = mysql_fetch_assoc($result)){
//iterate over all the fields
$emparray[] = $row;
}
echo json_encode($emparray);
这是我的回复:
[[],{"id":"1","username":"Liyari","password":"Karachi"},{"id":"12","username":"ssssss","password":"111111"},{"id":"121","username":"135","password":"Qasim"},{"id":"17","username":"nafees","password":"99999"},{"id":"134","username":"","password":""},{"id":"133","username":"","password":""},{"id":"135","username":"mustafa","password":"45612"},{"id":"131","username":"mustafa","password":"45612"},{"id":"132","username":"","password":""}]
问)为什么我在 Response 开始时得到空数组。
移除
$emparray[] = array();
或设为
$emparray = array();
那就可以正常工作了。
当你写类似
的东西时
$foo[] = $something;
在 php 中,您正在向数组末尾添加一个元素。
与
$emparray[] = array();
您正在添加和数组作为第一个元素,因为 $emparray
之前没有初始化,那是因为您在响应开始时得到一个空数组。
你应该改变
$emparray[] = array();
来自
$emparray = array();
这是我的 Php 代码。我是 php 的新人,我想得到 JSON.
的适当回应 $db_handle = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $db_handle )
{
die('Could not connect: ' . mysql_error());
}
else
$response["message"] = "Connected Succsessfully";
//echo json_encode($response);
$db_found = mysql_select_db($db, $db_handle);
// check for required fields
if($db_found)
{
// mysql inserting a new row
mysql_query('SET CHARACTER SET utf8');
$query = "SELECT * FROM users";
$result = mysql_query($query);
//iterate over all the rows
$emparray[] = array();
while($row = mysql_fetch_assoc($result)){
//iterate over all the fields
$emparray[] = $row;
}
echo json_encode($emparray);
这是我的回复:
[[],{"id":"1","username":"Liyari","password":"Karachi"},{"id":"12","username":"ssssss","password":"111111"},{"id":"121","username":"135","password":"Qasim"},{"id":"17","username":"nafees","password":"99999"},{"id":"134","username":"","password":""},{"id":"133","username":"","password":""},{"id":"135","username":"mustafa","password":"45612"},{"id":"131","username":"mustafa","password":"45612"},{"id":"132","username":"","password":""}]
问)为什么我在 Response 开始时得到空数组。
移除
$emparray[] = array();
或设为
$emparray = array();
那就可以正常工作了。
当你写类似
的东西时$foo[] = $something;
在 php 中,您正在向数组末尾添加一个元素。
与
$emparray[] = array();
您正在添加和数组作为第一个元素,因为 $emparray
之前没有初始化,那是因为您在响应开始时得到一个空数组。
你应该改变
$emparray[] = array();
来自
$emparray = array();