0
$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"}]}
4

3 回答 3

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;
于 2012-08-04T08:06:24.343 回答
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;
}
于 2012-08-04T08:45:34.193 回答
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"}]}
于 2017-08-08T18:17:50.643 回答