我是PHP的新手,我不明白为什么JSON字符串前面有一个额外的字ARRAY。
下面是JSON字符串的输出:
Array{"Users":[{"UserID":"1","FirstName":"lalawee","Email":"12345","Password":null},{"UserID":"2","FirstName":"shadowblade721","Email":"12345","Password":null},{"UserID":"3","FirstName":"dingdang","Email":"12345","Password":null},{"UserID":"4","FirstName":"solidsnake0328","Email":"12345","Password":null}],"success":1}
这是PHP文件:
<?php
/*
* Following code will list all the Users
*/
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// get all Users from Users table
$result = mysql_query("SELECT * FROM Users") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// Users node
$response["Users"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$user[] = array();
$user["UserID"] = $row["UserID"];
$user["FirstName"] = $row["FirstName"];
$user["Email"] = $row["Email"];
$user["Password"] = $row["Password"];
// push single User into final response array
array_push($response["Users"], $user);
}
// success
$response["success"] = 1;
echo $response;
// echoing JSON response
echo json_encode($response);
}
else {
// no Users found
$response["success"] = 0;
$response["message"] = "No Users found";
// echo no users JSON
echo json_encode($response);
}
?>
答案 0 :(得分:4)
删除
echo $response;
正在打印单词Array。如果您尝试回显数组,它将显示单词“Array”而不是打印数组本身的内容。使用print_r()函数显示数组的内容。
print_r($response);
答案 1 :(得分:2)
除了使用__to_string
魔术方法的类之外,echo
和print
只会输出变量值的字符串解释。数字类型(整数和浮点数),字符串和(我认为)布尔值具有简单的字符串表示。任何其他变量(数组,对象,资源)将不输出任何内容,输出变量类型或抛出致命错误。
对于数组和对象,print_r()
将遍历每个成员/属性并尝试将其转换为字符串(print_r是print_recursive的简写)。所以print_r($response)
将为您提供完整的数组。
请记住,通常整个数组仅对输出进行调试很有用。将数组的php字符串版本传递给javascript可能毫无用处。