Reputation: 765
I am querying my database Select * from Customer
the customer tables holds Name,Surname Address,age.
I want to be able to transform the query into a json object in the following object:
Customer:
[
{Name:"john", Surname:"Beta" ,Age:"23"},
{Name:"Fred", Surname:"alpha" ,Age:"31"}
];
Do you have any ideas?I tried to loop through the query and use merge_array.. but it MERGED the array as expected... Thank you for your time.
Upvotes: 2
Views: 8612
Reputation:
Because I am using PDO to handle database calls I used a foreach statement.
$grids = $db->run("DATABASE QUERY");
foreach ($grids as $row) {
$grid[] = $row;
}
$struct = array("Grid" => $grid);
print json_encode($struct);
Otherwise same code as above. Thanks Mario.
Upvotes: 0
Reputation: 145492
You just need to group into the expected nested structure:
while ($row = mysql_fetch_assoc($r)) {
$customer[] = $row;
}
$struct = array("Customer" => $customer);
print json_encode($struct);
Upvotes: 6
Reputation: 39773
Either use it yourself, or have a look at what MySQL to JSON is doing and implement something like it :)
Upvotes: 1
Reputation: 6840
If you have code like this:
$sql = "SELECT id as userid, fullname, userstatus
FROM sometable
WHERE userstatus = 1";
$result = mysql_query($sql);
seems like json_encode(mysql_fetch_assoc($result));
would do the job? Put in a foreach/while for all results...
Upvotes: 2