Intereting Posts
Проводка изображений через wp.uploadFile XML RPC Чтение данных сеанса из файла хранения сеанса как я могу читать файлы редактирования pptx / docx / xlsx с помощью PHP? Как сравнить два изображения для сходства (Не точные совпадения с MD5)? Самый быстрый способ преобразования строки в целое число в PHP Как вы разбиваете субзапросы на CakePHP 3? Правильный способ использования функции «Запомнить меня» в PHP FOSUserBundle Override Roles – свойства «роли» в «Acme \ DemoBundle \ Entity \ User» уже были объявлены, но должны быть объявлены только один раз Почему dns_get_record не показывает CNAME, когда я ЗНАЮ, что они существуют? Artisan, создание таблиц в базе данных Возврат случайного значения из массива с вероятностью, пропорциональной его значению Получить смещенные соседи массива возможно ли декодировать файл, закодированный защитой zend? отдельные дни недели с повторными встречами php PHPUnit не может найти класс исключения

Google Chart Api использует значение datetime

Привет, я хочу, чтобы в моей диаграмме отображалось время datetime, я сделал несколько поисков по стеку, и я нашел похожие проблемы, подобные этому, но я не мог понять, как это исправить.

Часть кода, который, я считаю, должен измениться, ниже.

<?php $DB_NAME = 'project'; $DB_HOST = 'localhost'; $DB_USER = 'root'; $DB_PASS = 'smogi'; include_once 'header.php'; $view = ($_GET['view']); $username2 =$_SESSION['username']; $firstDate= $_POST['firstdatepicker']; $lastDate= $_POST['lastdatepicker']; $typeValue = ($_POST['typeValue']); $startHour = ($_POST['startHour']); $firstMin = ($_POST['firstMin']); $lastHour = ($_POST['lastHour']); $lastMin = ($_POST['lastMin']); $firstTime = $startHour.':'.$firstMin.':00'; $lastTime = $lastHour.':'.$lastMin.':00'; $con = mysqli_connect('localhost','root','smogi','project'); /* Establish the database connection */ $mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME); if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } $sql="SELECT sensorValue,datetime FROM sensors WHERE username='$view' AND datetime BETWEEN '$firstDate''$firstTime' AND '$lastDate''$lastTime' AND typeValue='$typeValue' ORDER BY datetime DESC"; $result = mysqli_query($con,$sql); $rows = array(); $table = array(); $table['cols'] = array( // Labels for your chart, these represent the column titles. array('label' => 'Date Time', 'type' => 'date'), array('label' => 'Sensor Value', 'type' => 'number') ); /* Extract the information from $result */ foreach($result as $r) { $temp = array(); // The following line will be used to slice the chart $temp[] = array('v' => 'Date('.date('Y',strtotime($r['datetime'])).','.(date('n',strtotime($r['datetime'])) - 1).','.date('d',strtotime($r['datetime'])).',0,0,0)'); // Values of the each slice $temp[] = array('v' => (int) $r['sensorValue']); $rows[] = array('c' => $temp); } $table['rows'] = $rows; // convert data into JSON format $jsonTable = json_encode($table); //echo $jsonTable; ?> <html> <head> <!--Load the Ajax API--> <script type="text/javascript" src="https://www.google.com/jsapi"></script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.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() { // Create our data table out of JSON data loaded from server. var data = new google.visualization.DataTable(<?=$jsonTable?>); var options = { hAxis: {title: 'Date & Time'}, vAxis: {title: 'Sensor Values'}, title: 'Sensor Data', is3D: 'true', width: 900, height: 600 }; // Instantiate and draw our chart, passing in some options. var chart = new google.visualization.ScatterChart(document.getElementById('chart_div')); chart.draw(data, options); } </script> </head> <body> <!--this is the div that will hold the pie chart--> <div id="chart_div"></div> </body> </html> 

Теперь моя диаграмма выглядит так …

введите описание изображения здесь

и я хочу вместо 1000,2000 … 5000 отображать дату и время из данных, которые я показываю.

Моя таблица базы данных, содержащая дату и время, приведена ниже …

введите описание изображения здесь

Не могли бы вы мне помочь??? 🙂

Solutions Collecting From Web of "Google Chart Api использует значение datetime"

Я просто попробовал следующий код:

 <?php $rows = array(); $table = array(); $table['cols'] = array( // Labels for your chart, these represent the column titles. array('label' => 'Date Time', 'type' => 'date'), array('label' => 'Sensor Value', 'type' => 'number'), array('type' => 'string', 'role' => 'tooltip', 'p' => array('html' => 'true')), ); $result = array( array('datetime' => '2015-04-25 00:00:00', 'sensorValue' => 5), array('datetime' => '2015-04-25 14:30:00', 'sensorValue' => 10), array('datetime' => '2015-04-26 02:10:10', 'sensorValue' => 15), array('datetime' => '2015-04-26 12:10:10', 'sensorValue' => 17), array('datetime' => '2015-04-27 03:45:23', 'sensorValue' => 25), array('datetime' => '2015-04-28 15:34:00', 'sensorValue' => 4), ); /* Extract the information from $result */ foreach($result as $r) { $temp = array(); // The following line will be used to slice the chart $temp[] = array('v' => 'Date('.date('Y',strtotime($r['datetime'])).',' . (date('n',strtotime($r['datetime'])) - 1).','. date('d',strtotime($r['datetime'])).','. date('H',strtotime($r['datetime'])).','. date('i',strtotime($r['datetime'])).','. date('s',strtotime($r['datetime'])).')'); // Values of the each slice $temp[] = array('v' => (int) $r['sensorValue']); $temp[] = array('v' => 'This is a <b>custom</b> tooltip. Insert your data as you like: On the 25th of April, 2015 the sensor value was: <b>5</b>'); $rows[] = array('c' => $temp); } $table['rows'] = $rows; // convert data into JSON format $jsonTable = json_encode($table); ?> <html> <head> <script type="text/javascript" src="https://www.google.com/jsapi?autoload={ 'modules':[{ 'name':'visualization', 'version':'1', 'packages':['corechart'] }] }"></script> <script type="text/javascript"> google.setOnLoadCallback(drawChart); function drawChart() { var data = new google.visualization.DataTable(<?php echo $jsonTable; ?>); var options = { title: 'Company Performance', curveType: 'function', legend: { position: 'bottom' }, tooltip: {isHtml: true} }; var chart = new google.visualization.ScatterChart(document.getElementById('curve_chart')); chart.draw(data, options); } </script> </head> <body> <div id="curve_chart" style="width: 900px; height: 500px"></div> </body> </html> . <?php $rows = array(); $table = array(); $table['cols'] = array( // Labels for your chart, these represent the column titles. array('label' => 'Date Time', 'type' => 'date'), array('label' => 'Sensor Value', 'type' => 'number'), array('type' => 'string', 'role' => 'tooltip', 'p' => array('html' => 'true')), ); $result = array( array('datetime' => '2015-04-25 00:00:00', 'sensorValue' => 5), array('datetime' => '2015-04-25 14:30:00', 'sensorValue' => 10), array('datetime' => '2015-04-26 02:10:10', 'sensorValue' => 15), array('datetime' => '2015-04-26 12:10:10', 'sensorValue' => 17), array('datetime' => '2015-04-27 03:45:23', 'sensorValue' => 25), array('datetime' => '2015-04-28 15:34:00', 'sensorValue' => 4), ); /* Extract the information from $result */ foreach($result as $r) { $temp = array(); // The following line will be used to slice the chart $temp[] = array('v' => 'Date('.date('Y',strtotime($r['datetime'])).',' . (date('n',strtotime($r['datetime'])) - 1).','. date('d',strtotime($r['datetime'])).','. date('H',strtotime($r['datetime'])).','. date('i',strtotime($r['datetime'])).','. date('s',strtotime($r['datetime'])).')'); // Values of the each slice $temp[] = array('v' => (int) $r['sensorValue']); $temp[] = array('v' => 'This is a <b>custom</b> tooltip. Insert your data as you like: On the 25th of April, 2015 the sensor value was: <b>5</b>'); $rows[] = array('c' => $temp); } $table['rows'] = $rows; // convert data into JSON format $jsonTable = json_encode($table); ?> <html> <head> <script type="text/javascript" src="https://www.google.com/jsapi?autoload={ 'modules':[{ 'name':'visualization', 'version':'1', 'packages':['corechart'] }] }"></script> <script type="text/javascript"> google.setOnLoadCallback(drawChart); function drawChart() { var data = new google.visualization.DataTable(<?php echo $jsonTable; ?>); var options = { title: 'Company Performance', curveType: 'function', legend: { position: 'bottom' }, tooltip: {isHtml: true} }; var chart = new google.visualization.ScatterChart(document.getElementById('curve_chart')); chart.draw(data, options); } </script> </head> <body> <div id="curve_chart" style="width: 900px; height: 500px"></div> </body> </html> 

поэтому я изменил:

  1. array('label' => 'Date Time', 'type' => 'number') в array('label' => 'Date Time', 'type' => 'date')
  2. сформировала дату с 'Date(date("Y"),date("n") - 1,date("d"),0,0,0)' как описано здесь

Вот результат с html в подсказке:

введите описание изображения здесь

ОБНОВИТЬ

Если вам нужны специальные всплывающие подсказки, вот документ для него. См. Обновленный код выше, вам нужно внести три изменения для настройки всплывающих подсказок:

  1. добавьте столбец «virtual» в список столбцов (с помощью role = tooltip):

    array('type' => 'string', 'role' => 'tooltip', 'p' => array('html' => 'true')),

  2. добавьте значение для столбца в цикле:

    $temp[] = array('v' => 'This is a <b>custom</b> tooltip. Insert your data as you like: On the 25th of April, 2015 the sensor value was: <b>5</b>');

  3. и пусть jsapi знает, что содержимое html:

     var options = { ... tooltip: {isHtml: true} }; 

ОБНОВИТЬ

Чтобы настроить значения горизонтальной оси, вам нужно сначала взглянуть на это . Просто добавьте объект hAxis (и его format ) в объект параметров диаграммы:

  var options = { ... hAxis: { format: 'yyyy-Md' } }; 

и вы увидите что-то вроде:

введите описание изображения здесь