我想创建饼图或甜甜圈图,标签为storage_type
,storage_used
和storage_free
。 storage_type
的标签是字符串,storage_used
是数字,storage_free
是数字。在饼图中仅输出storage_free
,而不在storage_used
和storage_free
之间进行组合。我希望饼图在storage_used
和storage_free
之间结合起来。
<?php
$tmp=array();
require "configdashboard.php";
/*
select the 3 columns of interest, assinging aliases for laziness purposes
*/
$sql="select `storage_type` as `type`,`storage_used` as `used`, `storage_free` as `free`
from `storage`
where `storage_type`='fujitsu';";
if( $stmt = $connection->query( $sql ) ){
while( $row = $stmt->fetch_assoc() ) {
/* Add each row with named columns - which makes working with the JSON in Javascript easier IMO */
$tmp[] = array(
'type' => $row['type'],
'used' => $row['used'],
'free' => $row['free']
);
}
}
# create the JSON string
$json=json_encode( $tmp );
?>
<html>
<head>
</head>
<body>
<div id="chart_div" style="width: 500px; height: 55%; display: block; margin: auto;" ></div>
<script src='//www.gstatic.com/charts/loader.js'></script>
<script>
var my_2d=<?php echo $json;?>;
console.log(Object.keys(my_2d));
google.charts.load('current', {packages: ['corechart']});
google.charts.setOnLoadCallback( drawChart );
function drawChart(){
if( Object.keys( my_2d ).length > 0 ){
var json= my_2d ;
var dataTbl = new google.visualization.DataTable();
dataTbl.addColumn('string', 'type');
dataTbl.addColumn('number', 'used');
dataTbl.addColumn('number', 'free');
/*
you should be able to access the properties of
each record using names now rather than indices
*/
Object.keys( json ).map( k=>{
var obj=json[ k ];
var data=[
obj.type,
parseFloat( obj.used ),
parseFloat( obj.free )
];
dataTbl.addRow( data );
});
var options = {};
var chart = new google.visualization.PieChart( document.getElementById('chart_div') );
chart.draw( dataTbl, options );
}
}
</script>
</body>
</html>