Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php query into json

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.

like image 935
7dr3am7 Avatar asked Apr 22 '26 09:04

7dr3am7


2 Answers

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);
like image 50
mario Avatar answered Apr 23 '26 22:04

mario


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...

like image 21
NDM Avatar answered Apr 23 '26 23:04

NDM