Php query into json

7dr3am7 picture 7dr3am7 · Mar 4, 2011 · Viewed 8.5k times · Source

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.

Answer

mario picture mario · Mar 4, 2011

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);