使用 Chartjs 和 PHP 创建图表

Posted

技术标签:

【中文标题】使用 Chartjs 和 PHP 创建图表【英文标题】:create Chart using Chartjs and PHP 【发布时间】:2017-08-04 13:48:15 【问题描述】:

我需要使用chartJS创建一个从mysql获取数据的图表,下面是mysql表的示例输出:

+----+------------+----------+-----------------+----------
| ID | DATE       | Time     | Create | Delete | Product |
+----+------------+----------+-----------------+---------+
|  1 | 03/12/2017 | 09:00:00 |     28 |   1264 |      59 | 

我设法将数据转换为 JSON 格式,使用 toturial here,下面是 php 文件:

get.php

<?php

$DB_NAME = 'testDB';
$DB_HOST = 'localhost';
$db_port = '3306';
$DB_USER = 'test';
$DB_PASS = 'mysql';
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);

  if (mysqli_connect_errno()) 
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
  

  $result = $mysqli->query('Select * from (SELECT * FROM Stats ORDER BY id DESC LIMIT 48)t ORDER BY id ASC');
  $rows = array();
  $table = array();
  $table['cols'] = array(
    array('label' => 'Time', 'type' => 'string'),
   array('label' => 'ProductCreate', 'type' => 'number'),
   array('label' => 'ProductDelete', 'type' => 'number'),
   array('label' => 'ProductRenew', 'type' => 'number')

);
    foreach($result as $r) 

      $temp = array();

      $temp[] = array('v' => (string) $r['Time']); 
      $temp[] = array('v' => (int) $r['Create']);
      $temp[] = array('v' => (int) $r['Delete']);
      $temp[] = array('v' => (int) $r['Renew']);

      $rows[] = array('c' => $temp);
    

$table['rows'] = $rows;

// convert data into JSON format
$SubsStats = json_encode($table);
echo $SubsStats;


?>

我现在的问题是如何将 PHP 输出包含到我的 html 文件中并使用 ChartJS 绘制图表?

谢谢, 阿里

【问题讨论】:

使用上面的“SubsStats”json数据并传递给javacript函数,在chartJS支持的函数的帮助下创建图表。 【参考方案1】:

检查Example

var data = 
	labels : ["January","February","March",
              "April","May","June",
              "July","Agost","September",
              "October","November","December"],
	datasets : [
		
			fillColor : "rgba(252,233,79,0.5)",
			strokeColor : "rgba(82,75,25,1)",
			pointColor : "rgba(166,152,51,1)",
			pointStrokeColor : "#fff",
			data : <?php echo $res; ?>
		
	]



var options=					
	//Boolean - If we show the scale above the chart data			
	scaleOverlay : false,
	
	//Boolean - If we want to override with a hard coded scale
	scaleOverride : true,
	
	//** Required if scaleOverride is true **
	//Number - The number of steps in a hard coded scale
	scaleSteps : 14,
	//Number - The value jump in the hard coded scale
	scaleStepWidth : 5,
	//Number - The scale starting value
	scaleStartValue : 55,
	//String - Colour of the scale line	
	scaleLineColor : "rgba(20,20,20,.7)",
	
	//Number - Pixel width of the scale line	
	scaleLineWidth : 1,

	//Boolean - Whether to show labels on the scale	
	scaleShowLabels : true,
	
	//Interpolated JS string - can access value
	scaleLabel : "<%=value%>",
	
	//String - Scale label font declaration for the scale label
	scaleFontFamily : "'Arial'",
	
	//Number - Scale label font size in pixels	
	scaleFontSize : 12,
	
	//String - Scale label font weight style	
	scaleFontStyle : "normal",
	
	//String - Scale label font colour	
	scaleFontColor : "#666",	
	
	///Boolean - Whether grid lines are shown across the chart
	scaleShowGridLines : true,
	
	//String - Colour of the grid lines
	scaleGridLineColor : "rgba(0,0,0,.3)",
	
	//Number - Width of the grid lines
	scaleGridLineWidth : 1,	
	
	//Boolean - Whether the line is curved between points
	bezierCurve : true,
	
	//Boolean - Whether to show a dot for each point
	pointDot : true,
	
	//Number - Radius of each point dot in pixels
	pointDotRadius : 5,
	
	//Number - Pixel width of point dot stroke
	pointDotStrokeWidth : 1,
	
	//Boolean - Whether to show a stroke for datasets
	datasetStroke : true,
	
	//Number - Pixel width of dataset stroke
	datasetStrokeWidth : 2,
	
	//Boolean - Whether to fill the dataset with a colour
	datasetFill : true,
	
	//Boolean - Whether to animate the chart
	animation : false,

	//Number - Number of animation steps
	animationSteps : 60,
	
	//String - Animation easing effect
	animationEasing : "easeOutQuart",

	//Function - Fires when the animation is complete
	onAnimationComplete : null
;


//Get context with jQuery - using jQuery's .get() method.
var ctx = $("#myChart").get(0).getContext("2d");


new Chart(ctx).Line(data,options);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://www.chartjs.org/assets/Chart.js"></script>
<canvas id="myChart"  ></canvas>

PHP 代码 :- (以上 js 代码)

<?php 

$array = array(65,68,75,81,95,105,130,120,105,90,75,70);

$res = json_encode($array);
?>

【讨论】:

【参考方案2】:
$data = array(
    array("label"=> row['id'], "y"=> row['value']),
    array("label"=> row['column1'], "y"=> row['value1']),
    array("label"=> row['column2'], "y"=> row['value2']),
        );

?>

【讨论】:

以上是关于使用 Chartjs 和 PHP 创建图表的主要内容,如果未能解决你的问题,请参考以下文章

如何使用laravel将chartjs图表生成为pdf?

动态更新chartjs图表的值

Django chartjs多个图表堆叠

基于Canvas的Char.js库使用

使用 nodejs 和 chartjs 从 mongodb 插入和获取值

NodeJS上的ChartJS:错误图表未定义