将Mysql数据转换为JSON

时间:2016-03-14 21:41:00

标签: php mysql json

<?php
include("WIP/dbconnect.php")
?>
</head>

<?php
$link = Connection();
$result=mysql_query("SELECT `testLocation`.`Date`, 
    `testLocation`.`Serial`, `testLocation`.`State`, 
    `testLocation`.`Count` FROM `testLocation`",$link);

if($result!==FALSE){
    //create an array
    $emparray = array();
    while($row = mysql_fetch_array($result))
    {
        $emparray[] = $row;
    }
    echo json_encode($emparray);

    mysql_free_result($result);
    mysql_close();
}
?>

我目前正在尝试将我的mysql数据库中的一些数据转换为json格式,但出于某种原因,生成的数据并不是很好的格式。看起来像这样 Data Link

我获得了正确格式化的JSON数据,但我无法生成图表。我目前正在使用AmCharts.com生成图表。它说无法解析Json

  <script>

  var chart = AmCharts.makeChart( "chartdiv", {
    "type": "serial",
    "dataLoader": {
      "url": "index2.php"
    },
    "pathToImages": "http://www.amcharts.com/lib/images/",
    "categoryField": "Date",
    "dataDateFormat": "YYYY-MM-DD 00:00:00",
    "startDuration": 1,
    "categoryAxis": {
      "parseDates": true
    },
    "graphs": [ {
      "valueField": "Serial",
      "bullet": "round",
      "bulletBorderColor": "#FFFFFF",
      "bulletBorderThickness": 2,
      "lineThickness ": 2,
      "lineAlpha": 0.5
    }, {
      "valueField": "State",
      "bullet": "round",
      "bulletBorderColor": "#FFFFFF",
      "bulletBorderThickness": 2,
      "lineThickness ": 2,
      "lineAlpha": 0.5
    }, {
      "valueField": "Count",
      "bullet": "round",
      "bulletBorderColor": "#FFFFFF",
      "bulletBorderThickness": 2,
      "lineThickness ": 2,
      "lineAlpha": 0.5
    }]   } );

1 个答案:

答案 0 :(得分:1)

如果您使用mysql_fetch_assoc()而不是mysql_fetch_array(),您将只获得一个关联数组,而不是一个关联数组和数字数组。

while($row = mysql_fetch_assoc($result)) {
    $emparray[] = $row;
}
echo json_encode($emparray);

如果您使用mysql_fetch_object(),那么您可以轻松生成像这样的对象数组

while($row = mysql_fetch_object($result)) {
    $emparray[] = $row;
}
echo json_encode($emparray);
  

Manual mysql_fetch_assoc()

     

Manual mysql_fetch_array()

     

Manual mysql_fetch_object()