mysql - How create a response json with nested objects in php? -



mysql - How create a response json with nested objects in php? -

i want create json response nested json object , grouping actual results id_hotel

my actual json response

{ "tag": "cities", "success": 1, "error": 0, "items": 2, "item": [ { "id": "6194", "year": "2013", "city": "london", "start": "1", "id_hotel": "20001", "name": "hotel piccadilly", "address": "road 4", "number_fr": "7003", "district": "london city", "pr": "gb", "fres": "1", "mode": "night", "pos": "402", "pes": "33", "pis": "21", "pus": "456" }, { "id": "6194", "year": "2013", "city": "london", "start": "1", "id_hotel": "20001", "name": "hotel piccadilly", "address": "road 4", "number_fr": "7003", "district": "london city", "pr": "gb", "fres": "1", "mode": "day", "pos": "0", "pes": "1", "pis": "0", "pus": "1" } ] }

my php code encoding response

$query = "select * cities city = 'london'"; $result = mysql_query($query) or die(mysql_error()); // check empty result if (mysql_num_rows($result) > 0) { $response["item"] = array(); while ($row = mysql_fetch_array($result)) { // temp user array $product = array(); $product["id"] = $row["id"]; $product["year"] = $row["year"]; $product["city"] = $row["city"]; $product["start"] = $row["start"]; $product["id_hotel"] = $row["id_hotel"]; $product["name"] = $row["name"]; $product["address"] = $row["address"]; $product["number_fr"] = $row["number_fr"]; $product["district"] = $row["district"]; $product["pr"] = $row["pr"]; $product["fres"] = $row["fres"]; $product["mode"] = $row["mode"]; $product["pos"] = $row["pos"]; $product["pes"] = $row["pes"]; $product["pis"] = $row["pis"]; $product["pus"] = $row["pus"]; // force single product final response array array_push($response["item"], $product); } // success $response["items"] = mysql_num_rows($result); $response["success"] = 1; // echoing json response echo json_encode($response);

what desider

{ "tag": "cities", "success": 1, "error": 0, "items": 2, "item": [ { "id": "6194", "year": "2013", "city": "london", "start": "1", "id_hotel": "20001", "name": "hotel piccadilly", "address": "road 4", "number_fr": "7003", "district": "london city", "pr": "gb", "fres": "1", "mode": [{ "value" : "night", "pos": "402", "pes": "33", "pis": "21", "pus": "456" }, { "value" : "day", "pos": "0", "pes": "1", "pis": "0", "pus": "1" }] } ] }

thanks in advance attention!!

add alternative json_force_object in function. can read in http://tr2.php.net/manual/en/json.constants.php . json_encode($response, json_force_object) ;

php mysql json nested

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -