1

我正在尝试从 MySQL 表中获取数据并以以下格式创建 JSON 输出。

{
    markers: [
    {
       latitude: 57.7973333,
       longitude: 12.0502107,
       title: "Angered",
       content: "Representing :)"
    },
    {
       latitude: 57.6969943,
       longitude: 11.9865,
       title: "Gothenburg",
       content: "Swedens second largest city"
    }
  ]
}

这是我用来生成 JSON 的 PHP

$model  = array();

    $query = "SELECT title, content, lat, lng FROM locations_tbl";

    //Get records from database
    $result = mysql_query($query, $con);

    if(mysql_num_rows($result)) {
        while($e = mysql_fetch_assoc($result)) {
            $model['title'][]       = $e['title'];
            $model['content'][] = $e['content'];
            $model['lat'][]     = $e['lat'];
            $model['lng'][]     = $e['lng'];
        }
    }

    header('Content-type: application/json');
    print json_encode(array('marker'=>$model));

下面是我用上面的代码得到的输出:

{
   marker: {
      title: [
          "Marker 1",
          "Marker 2",
          "Marker 3",
          "Marker 4",
          "Marker 5"
       ],
       content: [
          "Text 1",
          "Text 2",
          "Text 3",
          "Text 4",
          "Text 5"
       ],
       lat: [
          "46.99065400",
          "47.03520400",
          "47.20387700",
          "47.62574900",
          "47.43443400"
       ],
       lng: [
          "-122.92164800",
          "-122.81614600",
          "-122.24486400",
          "-122.14453800",
          "-122.46088200"
       ]
   }
}

有什么建议么?

4

3 回答 3

3

像这样创建数组:

    $i = 0;
    while($e = mysql_fetch_assoc($result)) {
        $model[$i]['title']       = $e['title'];
        $model[$i]['content']     = $e['content'];
        $model[$i]['lat']         = $e['lat'];
        $model[$i]['lng']         = $e['lng'];
        $i++;
    }
于 2013-07-31T05:36:56.337 回答
2

尝试这个

       $i = 0;
       while($e = mysql_fetch_assoc($result)) {
            $model[$i]['title']       = $e['title'];
            $model[$i]['content'] = $e['content'];
            $model[$i]['lat']     = $e['lat'];
            $model[$i]['lng']     = $e['lng'];
            $i++;
        }

我希望它会有所帮助

于 2013-07-31T05:36:11.717 回答
2

您实际上从未为每个标记创建一个新数组:

$model = array("markers" => array());
if(mysql_num_rows($result)) {
    while($e = mysql_fetch_assoc($result)) {
        $marker = array();
        $marker['title']    = $e['title'];
        $marker['content']  = $e['content'];
        $marker['lat']      = $e['lat'];
        $marker['lng']      = $e['lng'];
        $model["markers"][] = $marker;
    }
}
于 2013-07-31T05:36:24.920 回答