$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;
Is there something wrong with this code? My output only displays the first row of my database.
{"userDetails":[{"userId":"1","userEmail":"EmailAddress@gmail.com","userLocation":"HomeAddress","userFirstName":"Allan","userLastName":"Knocks"}]}
Beware! Doing this in a loop will modify the same instance many times and you will end up with the same object added many times to your array:
In the end $object->userDetails will contain n references to the same object with the last set properties.
Instead you should create a new instance inside the loop :
Try this:
You can try
Your json will look like bellow