Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
522 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...