dragon202076 2013-07-31 05:33
浏览 71
已采纳

PHP MySQL JSON输出

I am trying take data from a MySQL table and create a JSON output in the below format.

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

Here is the PHP I am using to generate the JSON

$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));

Below is the output that I get with the above code:

{
   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"
       ]
   }
}

Any suggestions?

  • 写回答

3条回答 默认 最新

  • duanhe0817825 2013-07-31 05:36
    关注

    Create array like this :

        $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++;
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测