Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
517 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...