$retrieve = mysql_query("SELECT * FROM `users`") or die(mysql_error());
$object -> userDetails = array();
while($retrieveArray = mysql_fetch_array($retrieve))
{
$item -> userId = $retrieveArray['id'];
$item -> userEmail = $retrieveArray['email'];
$item -> userLocation = $retrieveArray['location'];
$item -> userFirstName = $retrieveArray['firstname'];
$item -> userLastName = $retrieveArray['lastname'];
$object ->userDetails[] = $item;
}
$json = json_encode($object);
echo $json;
这段代码有问题吗?我的输出只显示我数据库的第一行。
{"userDetails":[{"userId":"1","userEmail":"EmailAddress@gmail.com","userLocation":"HomeAddress","userFirstName":"Allan","userLastName":"Knocks"}]}
答案 0 :(得分:1)
试试这个:
$retrieve = mysql_query("SELECT id, email, location, firstname, lastname FROM `users`") or die(mysql_error());
$userDetails= array();
while($row = mysql_fetch_assoc($retrieve)) {
$userDetails[] = $row;
}
$json = json_encode(array('userDetails' => $userDetails));
echo $json;
答案 1 :(得分:1)
小心!在循环中执行此操作将多次修改同一实例,并且最终将向阵列添加多次相同的对象:
while($retrieveArray = mysql_fetch_array($retrieve))
{
$item -> userId = $retrieveArray['id'];
$item -> userEmail = $retrieveArray['email'];
$item -> userLocation = $retrieveArray['location'];
$item -> userFirstName = $retrieveArray['firstname'];
$item -> userLastName = $retrieveArray['lastname'];
//you are adding here the same object with changed properties.
$object ->userDetails[] = $item;
}
最后,$ object-> userDetails将包含对具有最后设置属性的同一对象的n个引用。
相反,你应该在循环中创建一个新实例:
while($retrieveArray = mysql_fetch_array($retrieve))
{
//new item (if there is a class Item)
$item = new Item();
// if $item is just a stdObject created on the fly then use
$item = new stdClass();
$item -> userId = $retrieveArray['id'];
$item -> userEmail = $retrieveArray['email'];
$item -> userLocation = $retrieveArray['location'];
$item -> userFirstName = $retrieveArray['firstname'];
$item -> userLastName = $retrieveArray['lastname'];
//you are adding here another object
$object ->userDetails[] = $item;
}
答案 2 :(得分:0)
你可以尝试
$sql = "SELECT * FROM users";
$result = $con->query($sql);
if ($result->num_rows > 0) {
$userDetails = array();
while ($row = $result->fetch_assoc()) {
$userData[] = array(
"id" => $row["id"],
"name" => $row["name"],
"email" => $row["email"],
);
}
} else {
echo "0 results";
}
$result1['regular'] = $userData;
$json = json_encode($result1);
echo $json;
你的json看起来像吼叫
{"regular":[{"id":"2","name":"enamul Haque","email":"ehaque95@gmail.com"},{"id":"55","name":"Rafiq","email":"era@gmail.com"}]}