Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
469 views
in Technique[技术] by (71.8m points)

php - "Array" Appearing Before JSON Ouput

I'm new to PHP and I don't understand why there is an extra word ARRAY infront of the JSON string.

Heres the output of JSON String:

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}

This is the PHP file:

<?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);
}
?>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Remove

echo $response;

which is printing the word Array. If you try to echo the array, it will display the word 'Array' rather than printing the content of an array itself. Use print_r() function to display the content of an array.

print_r($response);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...