php - Google 饼图和 PHP

标签 php javascript mysql json google-visualization

我希望在我的网站上有一个 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 的示例。

这是 another similar SO question 中的一个简短示例:

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

关于php - Google 饼图和 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11494191/

相关文章:

PHP 批处理

php - 如何从 smarty 模板中的 URL 访问变量值?

php - 发布生产代码的最佳方式

javascript - 动态变化图表系列extjs 4

mysql - 带日期的 Cron 文件名正在传递 Y_m_d 而不是实际日期

java - 如何用 PHP 或 Java 发送电子邮件

javascript - 从两个不同的数组创建一个 JSON 对象

javascript - 如何将 getJson 的响应保存在全局变量中?

php - 如果primary,auto increment field的列名不是id,可以使用$this->db->insert_id()函数

php - 如何从mysql结果中获取表名?