Maria Maria - 10 months ago 46
JSON Question

How to create json response

I am developing an android app by using google map v2, at server end i am using php and mysql database. In database there are already many location coordinates in terms of latitudes and longitudes are stored, so what i want is when user turn On the app the backgroud service fetch all these latitudes and longitudes from database through server and display on the map, but i am stuck at php end. Suppose this is my database data

+---------+---------+---------+--------+
| uid | lat | long | loc |
+---------+---------+------- -+--------+
| 1 |Value1 A1|Value2 A1| A |
+---------+---------+---------+--------+
| 2 |Value1 B2|Value2 B2| B |
+---------+---------+---------+--------+
| 3 |Value1 C3|Value2 C3| C |
+---------+---------+---------+--------+
| 4 |Value1 D4|Value2 D4| D |
+---------+---------+---------+--------+


This query can give me data row wise
$result = mysql_query("SELECT uid, lat, long, loc FROM table")
but how can i store this data in some array sequence wise so when encode it in json it will generate similar response like this

[
{
"uid": "1": [
{
"lat": "Value1_A1",
"lon": "Value2_A1"
"loc": "A"
}

]
},
{
"uid": "2": [
{
"lat": "Value1_B2",
"lon": "Value2_B2"
"loc": "B"
}

]
},
{
"uid": "3": [
{
"lat": "Value1_C3",
"lon": "Value2_C3"
"loc": "C"
}

]
},
{
"uid": "4": [
{
"lat": "Value1_D4",
"lon": "Value2_D4"
"loc": "D"
}

]
},
and so on...............
]


Please help me as i am serching for the solution from last two days but unable to find any reasonable solution.

Answer Source

Try mysql_fetch_assoc:

$json = array();
while ($row = mysql_fetch_assoc($result)) {
    $json[$row['uid']] = array(
       'lat' => $row['lat'],
       'lon' => $row['lon'],
       'loc' => $row['loc']
    );
}
echo json_encode($json);

You should use MySQLi or PDO_MySQL instead of mysql_.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download