Мне нужно сделать такую диаграмму, это диаграмма Google, но она берет значения из электронной таблицы онлайн, и мне нужно указать локальные значения.
Я перепробовал все, но ничего не получалось.
Кто-нибудь знает что-нибудь для этого?
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {'packages': ['table', 'map', 'corechart']});
google.setOnLoadCallback(initialize);
function initialize() {
// The URL of the spreadsheet to source data from.
var query = new google.visualization.Query(
'https://spreadsheets.google.com/pub?key=pCQbetd-CptF0r8qmCOlZGg');
query.send(draw);
}
function draw(response) {
if (response.isError()) {
alert('Error in query');
}
var ticketsData = response.getDataTable();
var chart = new google.visualization.ColumnChart(
document.getElementById('chart_div'));
chart.draw(ticketsData, {'isStacked': true, 'legend': 'bottom',
'vAxis': {'title': 'Number of tickets'}});
var geoData = google.visualization.arrayToDataTable([
['Lat', 'Lon', 'Name', 'Food?'],
[51.5072, -0.1275, 'Cinematics London', true],
[48.8567, 2.3508, 'Cinematics Paris', true],
[55.7500, 37.6167, 'Cinematics Moscow', false]]);
var geoView = new google.visualization.DataView(geoData);
geoView.setColumns([0, 1]);
var table =
new google.visualization.Table(document.getElementById('table_div'));
table.draw(geoData, {showRowNumber: false});
var map =
new google.visualization.Map(document.getElementById('map_div'));
map.draw(geoView, {showTip: true});
// Set a 'select' event listener for the table.
// When the table is selected, we set the selection on the map.
google.visualization.events.addListener(table, 'select',
function() {
map.setSelection(table.getSelection());
});
// Set a 'select' event listener for the map.
// When the map is selected, we set the selection on the table.
google.visualization.events.addListener(map, 'select',
function() {
table.setSelection(map.getSelection());
});
}
</script>
</head>
<body>
<table align="center">
<tr valign="top">
<td style="width: 50%;">
<div id="map_div" style="width: 400px; height: 300;"></div>
</td>
<td style="width: 50%;">
<div id="table_div"></div>
</td>
</tr>
<tr>
<td colSpan=2>
<div id="chart_div" style="align: center; width: 700px; height: 300px;"></div>
</td>
</tr>
</table>
</body>
</html>
Я использую диаграмму как это.
Подключитесь к базе данных и сделайте запрос:
$db = new mysqli('localhost', 'user', 'password', 'database');
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
$sql = <<<SQL
SELECT *
FROM `log`
WHERE `type` = 'order'
SQL;
if(!$result = $db->query($sql)){
die('There was an error running the query [' . $db->error . ']');
}
В моем случае у меня есть метка времени, и я использую разные массивы для разных графиков.
while($row = $result->fetch_assoc()) {
$orders_year_month_day[date('Y', $row['timestamp'])][date('n', $row['timestamp'])][date('j', $row['timestamp'])][] = $row['wid'];
$orders_hour[date('G', $row['timestamp'])][] = $row['wid'];
if (date('Y-n-d', $row['timestamp']) == date('Y-n-d')) {
$orders_hour_today[date('G', $row['timestamp'])][] = $row['wid'];
}
$orders_hour_month[date('G', $row['timestamp'])][date('n', $row['timestamp'])][] = $row['wid'];
}
Вышеупомянутые 3 массива производят следующее:
$orders_year_month_day
Array
(
[2015] => Array
(
[5] => Array
(
[20] => Array
(
[0] => 12:11:13
[1] => 12:14:51
[2] => 12:39:44
[3] => 13:03:49
[4] => 13:10:15
$orders_hour
Array
(
[12] => Array
(
[0] => 12:11:13
[1] => 12:14:51
[2] => 12:39:44
[3] => 12:44:22
$orders_hour_month
Array
(
[12] => Array
(
[5] => Array
(
[0] => 12:11:13
[1] => 12:14:51
[2] => 12:39:44
[3] => 12:44:22
[4] => 12:49:24
Затем я делаю еще один проход в вышеупомянутых массивах, чтобы получить данные, необходимые для 3 графиков.
// Total signups today per hour.
if (!empty($orders_hour_today)) {
foreach ($orders_hour_today as $hour => $signups) {
$orders_hour_today_total[$hour] = count($signups);
}
ksort($orders_hour_today_total);
}
// Total signups across all months per hour.
foreach ($orders_hour as $hour => $signups) {
$orders_hour_total[$hour] = count($signups);
}
ksort($orders_hour_total);
// Total signups in a month per day.
foreach ($orders_year_month_day[$show_year] as $month => $days) {
foreach ($days as $day => $orders) {
$orders_per_day_in_month[$month][$day] = count($orders);
}
}
// Total signpus for each month per hour.
foreach ($orders_hour_month as $hour => $months) {
foreach ($months as $month => $signups) {
$order_hour_month_total[$hour][$month] = count($signups);
$order_hour_this_month_total[$hour][date('n')] = count($signups);
}
}
ksort($order_hour_month_total);
И тогда я создаю списки данных для диаграмм:
$data_add_rows = '';
$data_add_rows_days = '';
$data_add_rows_hour = '';
$data_add_rows_hour_today = '';
foreach ($orders_per_day_in_month as $month => $days) {
$orders_counted_per_month[$month] = array_sum($days);
$data_add_rows .= '["' . $month . '", ' . $orders_counted_per_month[$month] . ', ' . $orders_counted_per_month[$month] . "],";
if ($month == $show_month) {
foreach ($days as $day => $number_of_signups) {
$data_add_rows_days .= '["' . $day . '", ' . $number_of_signups . ', ' . $number_of_signups . "],";
}
}
}
foreach ($orders_hour_total as $hour => $signups_total) {
$data_add_rows_hour .= '["' . $hour . '", ' . $signups_total . ', ' . $signups_total . "],";
}
if (!empty($orders_hour_today_total)) {
foreach ($orders_hour_today_total as $hour => $signups_total) {
$data_add_rows_hour_today .= '["' . $hour . '", ' . $signups_total . ', ' . $signups_total . "],";
}
$data_add_rows_hour_today = rtrim($data_add_rows_hour_today, ",");
} else {
$data_add_rows_hour_today = '[0, 0, 0]';
}
$data_add_rows = rtrim($data_add_rows, ",");
$data_add_rows_days = rtrim($data_add_rows_days, ",");
$data_add_rows_hour = rtrim($data_add_rows_hour, ",");
Это даст
// $data_add_rows
["5", 169, 169],["6", 549, 549],["7", 392, 392],["8", 513, 513],["9", 482, 482]
И тогда у меня есть разметка вот так:
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['corechart', 'bar']});
google.setOnLoadCallback(drawBasic);
function drawBasic() {
// Month
var data = google.visualization.arrayToDataTable([
['Month', 'Signups 2015', { role: 'annotation' }],
<?php print $data_add_rows; ?>
]);
var options = {
title: 'Website Signups / <?php print $total_signups; ?>',
chartArea: {width: '50%'},
hAxis: {
title: 'Total signups for month',
minValue: 0
},
vAxis: {
title: 'Month'
},
height: 600
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
</head>
<body>
<div id="chart_div"></div>
</body>
Других решений пока нет …