2012-07-29 84 views
-1

我是PHP新手,我不明白为什么JSON字符串中有一个额外的字ARRAY。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); 
} 
?> 
+1

请尝试使用有用的非尖叫标题为您的线程。通过用PHP标记您的问题,我们知道您需要PHP的帮助。如果你有一个内容丰富的标题,你可能会得到更多的答案。 – 2012-07-29 06:35:20

回答

4

删除

echo $response; 

正在打印的字阵列。如果您尝试回显数组,它将显示单词“数组”,而不是打印数组本身的内容。使用print_r()函数来显示数组的内容。

print_r($response); 
2

随着使用该__to_string魔术方法类例外,echoprint只会输出变量的值的字符串解释。数字类型(整数和浮点数),字符串和(我认为)布尔值具有直接的字符串表示形式。任何其他变量(数组,对象,资源)将不输出任何内容,它们的变量类型,或者引发致命错误。

对于数组和对象,print_r()将遍历每个成员/属性并试图将其转换为字符串(print_r是print_recursive的缩写)。所以print_r($response)会给你完整的数组。

请记住,通常整个阵列仅用于调试输出。将一个数组的php字符串版本传递给javascript可能是无用的。

+0

+1为彻底 – 2012-07-29 07:25:32