PHP:对于Google图表,datetime字符串为json datetime [英] PHP: datetime string to json datetime for Google Chart

查看:47
本文介绍了PHP:对于Google图表,datetime字符串为json datetime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经努力了几天,试图将datetime字符串转换为json datetime以包含在Google图表中,现在正在寻求帮助.

I've been struggling for a few days trying to convert a datetime string to a json datetime for inclusion in a Google Chart and am now looking for some help.

我拥有的日期格式为"2008-01-15 14:30:45",我认为在将其插入到数组,然后将其转换为Google图表的JSON格式.

The format of the date I have is "2008-01-15 14:30:45" which I believe needs to be converted to Date(2008, 0, 15, 14, 30, 45) before being inserted into an array and then being converted to JSON format for a google chart.

目标主要是能够向图形添加趋势线,但是也可以使时间刻度正确:).

The goal is primarily to be able to add a trendline to the graph but it would be nice to have the timescale correct too :).

代码紧随其后.

任何帮助都将不胜感激.

Any help greatly appreciated.

SteveW

    <?php 

    require_once 'dbconfig.php';
    /* Your Database Name */
    $dbname = 'speedtest';

    try {
    /* Establish the database connection */
    $conn = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    //DOWNLOAD CHART
    $dresult = $conn->query('SELECT starttime, download FROM speeddata');

    $drows = array();
    $dtable = array();
    $dtable['cols'] = array(

    // Labels for your chart, these represent the column titles.
    array('label' => 'StartTime', 'type' => 'string'), //change 'string' to datetime
    array('label' => 'Download Speed', 'type' => 'number'),

);
    /* Extract the information from $result */
    foreach($dresult as $d) {

      $dtemp = array();

      // the following line will be used to slice the chart
      $dtemp[] = array('v' =>  $d['starttime']); //starttime to Date(2008, 0, 15, 14, 30, 45) format?
      // Values of each slice
      $dtemp[] = array('v' => (DOUBLE) $d['download']); 
      // $temp[] = array('v' => (DOUBLE) $r['server_name']); 

      $drows[] = array('c' => $dtemp);
    }

    $dtable['rows'] = $drows;

    // convert data into JSON format
    $djsonTable = json_encode($dtable);
    //echo $djsonTable;
    } catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
    }

    ?>

    <html lang="en">
    <head>
    <meta charset="UTF-8">

    <!--Reload page on resize-->
    <script type="text/javascript">
    var currheight = document.documentElement.clientHeight;
    window.onresize = function(){
        if(currheight != document.documentElement.clientHeight) {
        location.replace(location.href);
        }    
    }
    </script>
    <!--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(downloadChart);


    function downloadChart() {

      // Create our data table out of JSON data loaded from server.
      var ddata = new google.visualization.DataTable(<?=$djsonTable?>);
      var options = {
           //title: 'Speedtest Data',
           //titleposition: 'none',
          is3D: 'true',
          width: '100%',
          height: 500,
          hAxis:{title: 'Time', 
                direction:1, 
                slantedText:true, 
                slantedTextAngle:90,
                textStyle : { fontSize: 8} // or the number you want
                },
          vAxis:{title: 'Speed Mbit/s'},
          legend: { position: 'bottom' },
          chartArea: { top: 45, height: '40%',
                        backgroundColor: {
                        stroke: '#ccc',
                        strokeWidth: 1},

            }
            //trendlines: { 0: {color: 'green',} }    // Draw a trendline for data series 0.        


        };
      // Instantiate and draw our chart, passing in some options.
      // Do not forget to check your div ID

      var chart = new google.visualization.LineChart(document.getElementById('download_chart_div'));
      chart.draw(ddata, options);

    }

    </script>

</head>

 <body class="site">

<main class="site-content">
    <!--this is the div that will hold the chart-->

    <div id="chart_title">Download Speed</div>
    <div id="download_chart_div"></div>
    <hr><br>


    </main>

  </body>
</html>

推荐答案

我试图找到一种在您的问题上不那么复杂的解决方案.感谢Symfony中的JSONResponse,我已经在PHP中发送了JSON响应.我在PHP中所做的一个小技巧是将dateTime转换为'Y,m,d'格式.

I tried to find a solution less complicated at your issue. I've send a JSON response in PHP thanks to JSONResponse in Symfony. The little trick I've made in PHP¨is to transform the dateTime to 'Y, m , d' format.

$tableTimeline = [];
    foreach ($resources as $resource)
    {
        if($this->get('platform.timeline')->computeIntervals($resource->getBusiness())[0] != null)
        array_push($tableTimeline, [
            $resource->getTechnician()->getUsername(),
            $resource->getBusiness()->getName()." (".$this->get('platform.gantt')->baseTime($resource->getBusiness())." h/s)",
            // format -> new Date(1809, 3, 26)
            date_format($this->get('platform.timeline')->computeIntervals($resource->getBusiness())[0], 'Y, m, d'),
            date_format($this->get('platform.timeline')->computeIntervals($resource->getBusiness())[1], 'Y, m, d'),
        ]);
    }

    return new JsonResponse($tableTimeline);

然后我通过Ajax调用检索了JS中的数据,并将JSON对象修改为一个数组

Then I retrieved the data in JS thanks to an Ajax call and modify the JSON object to an array

success: function (chart_values) {
                let arrayData = $.map(chart_values, function (value, index) {
                    return [value];
                });
                arrayData = changeToDate(arrayData);
                draw_chart(arrayData); // call your drawing function!
            }

此代码的小技巧位于changeToDate函数中->我更改了2&从字符串日期("Y,m,d")到可读的JS日期3列

The little trick of this code is located in the changeToDate function -> I changed the values of the 2 & 3 columns from string dates ('Y, m,d') to readable JS dates

 function changeToDate(arrayData) {
        arrayData.forEach(data => {
            let startDate = new Date(data[2]);
            let endDate = new Date(data[3]);
            data[2] = startDate;
            data[3] = endDate;
        });
        return arrayData;
    }

然后我借助draw_chart函数绘制了图表

Then I drew the chart thanks to draw_chart function

这篇关于PHP:对于Google图表,datetime字符串为json datetime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆