繁体   English   中英

Google饼图和PHP

[英]Google Pie Charts and PHP

我想在我的网站上有一个Google饼图。 饼形图将填充数据库中的数据。 我在https://developers.google.com/chart/interactive/docs/php_example上查找了一些示例,但是当涉及JSON格式时我迷路了。

这里有些例子:

 <html>
   <head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="jquery-1.6.2.min.js"></script>
<script type="text/javascript">

// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});

// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);

function drawChart() {
  var jsonData = $.ajax({
      url: "getData.php",
      dataType:"json",
      async: false
      }).responseText;

  // Create our data table out of JSON data loaded from server.
  var data = new google.visualization.DataTable(jsonData);

  // Instantiate and draw our chart, passing in some options.
  var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
  chart.draw(data, {width: 400, height: 240});
}

</script>
</head>

<body>
  <!--Div that will hold the pie chart-->
  <div id="chart_div"></div>
</body>
</html>

这是我迷路的代码段(getData.php):

 <?php 

// This is just an example of reading server side data and sending it to the client.
// It reads a json formatted text file and outputs it.

 $string = file_get_contents("sampleData.json");
 echo $string;

// Instead you can query your database and parse into JSON etc etc

 ?>

我的数据存储在数据库中,而不是JSON格式。 如何使用MySQL数据库查询使用JSON格式? 如果您有一些示例或演示,我将不胜感激。

首先要做的是看一下有关json_encode()方法的PHP手册。 它提供了有关如何使用PHP生成JSON的示例。

这是另一个类似的SO问题的简短示例:

// Get your data from DB
$sth = mysql_query("SELECT ...");
// Create an array
$rows = array();
// Loop over the DB result and add it to your array
while($r = mysql_fetch_assoc($sth)) {
    $rows[] = $r;
}
// Use json_encode() to turn the array into JSON
print json_encode($rows);

如果需要重命名数据库列,以使JSON数据在属性上获得的名称不同于数据库中使用的名称,则可以在SQL中使用AS

SELECT blog_title as title ...

只是echo php result in var data = new google.visualization.DataTable([<?php echo $result ;?>]);

您将按照以下格式从数据库获取数据

             ['Task', 'Hours per Day'],
                      ['Work',     11],
                      ['Eat',      2],
                      ['Commute',  2],
                      ['Watch TV', 2],
                      ['Sleep',    7]

我认为这对您很有用,我在热图中使用相同的逻辑

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM