使用 Google Charts 为这个 JSON 绘制柱形图 var_dump();数据

Posted

技术标签:

【中文标题】使用 Google Charts 为这个 JSON 绘制柱形图 var_dump();数据【英文标题】:Draw a column chart using Google Charts for this JSON var_dump(); data 【发布时间】:2015-07-20 16:49:31 【问题描述】:

如何使用 Google-Visualization 将以下 php-JSON 代码放入柱形图中?

<?php
    /* Connect  to database */
    $mysqli = new mysqli("localhost","root","123","charts");
    if(mysqli_connect_errno())
      trigger_error('Connection failed: '.$mysqli->error);
    

    /* Build the query */
    $query = "SELECT a.item_code,a.total,a.date FROM chart_values a, (SELECT DISTINCT item_code FROM chart_values GROUP BY item_code,date) b WHERE a.item_code = b.item_code";

    /* Loop through the results and build a JSON array for the data table */
    $result = $mysqli->query($query);

    $table = array();
    while ($row = $result->fetch_array(MYSQLI_ASSOC)) 

                if (!isset($table[$row['item_code']])) 
                    $table[$row['item_code']] = array(
                          'total' => array(),
                          'date' => array()
              );
           

            $table[$row['item_code']]['total'][] = $row['total'];
            $table[$row['item_code']]['date'][] = $row['date'];
           
    echo var_dump($table);
    $data = json_encode($table);
?>

var_dump($table); 结果是这样的:

array(3)  ["Scratch card 1.0 JD"]=> array(2)  ["total"]=> array(3)  [0]=> string(3) "411" [1]=> string(3) "333" [2]=> string(3) "123"  ["date"]=> array(3)  [0]=> string(10) "2013-04-01" [1]=> string(10) "2014-03-01" [2]=> string(10) "2015-02-01"   ["Scratch card 2.0 JD"]=> array(2)  ["total"]=> array(3)  [0]=> string(3) "212" [1]=> string(3) "500" [2]=> string(3) "608"  ["date"]=> array(3)  [0]=> string(10) "2013-04-01" [1]=> string(10) "2014-03-01" [2]=> string(10) "2015-02-01"   ["Scratch card 3.0 JD"]=> array(2)  ["total"]=> array(3)  [0]=> string(3) "234" [1]=> string(3) "345" [2]=> string(3) "456"  ["date"]=> array(3)  [0]=> string(10) "2013-04-01" [1]=> string(10) "2014-03-01" [2]=> string(10) "2015-02-01"   

【问题讨论】:

谢谢 ZygD,你知道我该怎么做吗? 【参考方案1】:
<?php
    /* Connect  to database */
    $mysqli = new mysqli("localhost","root","123","charts");
    if(mysqli_connect_errno())
      trigger_error('Connection failed: '.$mysqli->error);
    

    /* Build the query */
    $query = "SELECT a.item_code,a.total,a.date FROM chart_values a, (SELECT DISTINCT item_code FROM chart_values GROUP BY item_code,date) b WHERE a.item_code = b.item_code";

    /* Loop through the results and build a JSON array for the data table */
    $result = $mysqli->query($query);

    $table = array();
    while ($row = $result->fetch_array(MYSQLI_ASSOC)) 

                if (!isset($table[$row['item_code']])) 
                    $table[$row['item_code']] = array(
                          'total' => array(),
                          'date' => array()
              );
           

            $table[$row['item_code']]['total'][] = $row['total'];
            $table[$row['item_code']]['date'][] = $row['date'];
           
    //echo var_dump($table);
    $datas = $table;
   // echo $datas; // insert this data to your database, cause this $data is string.

    $googleData = array('Date');
    foreach($datas as $key => $data)
        $googleData[] = $key;
    

    for($i=0;$i<count($datas);$i++)
        foreach($datas as $key => $data)
            if(!in_array($data['date'][$i], $googleData))
                $googleData[] = $data['date'][$i];
            
            $googleData[] = $data['total'][$i];
        
    

    $googleData = json_encode(array_chunk($googleData,count($datas)+1));
    print_r($googleData);
?>

只需从您的 js 代码中删除注释并将其更改为 $googleData

var data = google.visualization.arrayToDataTable(JSON.parse('<?php echo $googleData; ?>'));


这是我的代码

<script src="https://www.google.com/jsapi"></script>
<body>
    <div style="width:90%; height:500px;" id="columnchart_material" style="width: 1000px; height: 500px;"></div>
</body>

<?php 

$datas = '"Scratch card 1.0 JD":"total":["411","333","123"],"date":["2013-04-01","2014-03-01","2015-02-01"],"Scratch card 2.0 JD":"total":["212","500","608"],"date":["2013-04-01","2014-03-01","2015-02-01"],"Scratch card 3.0 JD":"total":["234","345","456"],"date":["2013-04-01","2014-03-01","2015-02-01"]';

$datas = json_decode($datas,true);
// echo '<pre>';
// print_r($datas);

        $googleData = array('Date');
        foreach($datas as $key => $data)
            $googleData[] = $key;
        

        for($i=0;$i<count($datas);$i++)
            foreach($datas as $key => $data)
                if(!in_array($data['date'][$i], $googleData))
                    $googleData[] = $data['date'][$i];
                
                $googleData[] = $data['total'][$i];
            
        

        $googleData = json_encode(array_chunk($googleData,count($datas)+1));
        // print_r($googleData);
?>
<script type="text/javascript">
google.load("visualization", "1.1", 
    packages: ["bar"]
);
google.setOnLoadCallback(drawChart);

function drawChart() 

    var data = google.visualization.arrayToDataTable(JSON.parse('<?php echo $googleData; ?>'));

    var options = 
        chart: 
            title: 'Company Performance',
            subtitle: 'Sales, Expenses, and Profit: 2014-2017',
        
    ;

    var chart = new google.charts.Bar(document.getElementById('columnchart_material'));

    chart.draw(data, options);

</script>

新答案

<?php
    /* Connect  to database */
    $mysqli = new mysqli("localhost","root","123","charts");
    if(mysqli_connect_errno())
      trigger_error('Connection failed: '.$mysqli->error);
    

    /* Build the query */
    $query = "SELECT a.item_code,a.total,a.date FROM chart_values a, (SELECT DISTINCT item_code FROM chart_values GROUP BY item_code,date) b WHERE a.item_code = b.item_code";

    /* Loop through the results and build a JSON array for the data table */
    $result = $mysqli->query($query);

    $table = array();
    while ($row = $result->fetch_array(MYSQLI_ASSOC)) 

                if (!isset($table[$row['item_code']])) 
                    $table[$row['item_code']] = array(
                          'total' => array(),
                          'date' => array()
              );
           

            $table[$row['item_code']]['total'][] = $row['total'];
            $table[$row['item_code']]['date'][] = $row['date'];
           
    echo var_dump($table);
    $datas = json_encode($table);

$datas = json_decode($datas,true);
// echo '<pre>';
// print_r($datas);

        $googleData = array('Date');
        foreach($datas as $key => $data)
            $googleData[] = $key;
        

        for($i=0;$i<count($datas);$i++)
            foreach($datas as $key => $data)
                if(!in_array($data['date'][$i], $googleData))
                    $googleData[] = $data['date'][$i];
                
                $googleData[] = $data['total'][$i];
            
        

        $googleData = json_encode(array_chunk($googleData,count($datas)+1));
        // print_r($googleData);
?>



<script src="https://www.google.com/jsapi"></script>
<body>
    <div style="width:90%; height:500px;" id="columnchart_material" style="width: 1000px; height: 500px;"></div>
</body>


<script type="text/javascript">
google.load("visualization", "1.1", 
    packages: ["bar"]
);
google.setOnLoadCallback(drawChart);

function drawChart() 

    var data = google.visualization.arrayToDataTable(JSON.parse('<?php echo $googleData; ?>'));

    var options = 
        chart: 
            title: 'Company Performance',
            subtitle: 'Sales, Expenses, and Profit: 2014-2017',
        
    ;

    var chart = new google.charts.Bar(document.getElementById('columnchart_material'));

    chart.draw(data, options);

</script>

【讨论】:

仍然没有发生任何事情 :( 天哪,我暂时闭上了眼睛.. 你能检查一下吗:***.com/questions/18763900/… 我读到使用谷歌图表你必须使用这些数组 table['cols'] 和table['rows'] idk .. 对于某种 google api,只能识别我认为的那些:/ 或者我错了,因为我已经看到很多使用相同方法的人的例子,链接中的这个方法跨度> 您可以提醒您的 javascript 文件中的 $googleData 吗?如果这可以工作, var data = google.visualization.arrayToDataTable(JSON.parse()); 检查一下,jsfiddle.net/0a2maksv/7 已经正常工作了吗?这只是因为 $googleData 无法传输到您的 javascript 文件 我猜是因为我们没有使用我发送给您的示例中的语法,您可以看看这个:developers.google.com/chart/interactive/docs/reference 感谢 JOSUA,我编辑了新的答案并为我工作谢谢伙计你太棒了!

以上是关于使用 Google Charts 为这个 JSON 绘制柱形图 var_dump();数据的主要内容,如果未能解决你的问题,请参考以下文章

Google Charts interpolateNulls无效

Google Charts API更改字体

react-google-charts点击事件不起作用

如何在Scatter Google Charts中显示两种不同的颜色?

Google Charts显示选项

Google Charts LogScale无效