简体   繁体   English

来自MySQL JSON编码数组的Google图表

[英]Google Charts from MySQL JSON Encoded Array

I'm having one heck of a time here, how can I draw up the chart from a json_encoded mySQL array? 我在这里度过了很长时间,如何从json_encoded mySQL数组中绘制图表?

Data Retrieval (simply associated array from a PDO query): 数据检索(来自PDO查询的简单关联数组):

    if($cCt > 0){
        header('Content-Type:application/json');    
        $table['cols'] = array(
                                array('id'=>'Date', 'label'=>'Date', 'type'=>'string'),
                                array('id'=>'Carbs', 'label'=>'Carbs', 'type'=>'number'),
                                array('id'=>'Sugar', 'label'=>'Sugar', 'type'=>'number'),
                                array('id'=>'Units', 'label'=>'Units', 'type'=>'number'));
        for($i=0; $i<$cCt; ++$i){
            $W = (isset($_GET['which'])) ? (int)$_GET['which'] : 0;
            switch($W){
                case 1: // weekly
                case 2: // monthly
                case 3: // yearly
                    $date = date('m/d', strtotime($CNums[$i]['Date']));
                    break;
                case 4: // daily
                    $date = date('m/d g:i a', strtotime($CNums[$i]['Date']));
                    break;
                default:
                    $date = date('m/d g:i a', strtotime($CNums[$i]['Date']));
                    break;
            }
            $rows[] = array('c'=>array('v'=>$date, 'v'=>$CNums[$i]['Carbs'], 'v'=>$CNums[$i]['Sugar'], 'v'=>$CNums[$i]['Units']));
        }
        $table['rows'] = $rows; 
        echo json_encode($table, JSON_NUMERIC_CHECK);
    }else{
        echo ErrorBox('Please login to see your charts.');
    }

Code Attempt: 代码尝试:

<script type="text/javascript">

    google.load('visualization', '1.0', {'packages':['corechart']});
    google.setOnLoadCallback(drawChart);
    function drawChart() {
        var $dUrl = "/assets/php/charts/chart.data.php?_=<?php echo time(); ?>&which=<?php echo (isset($which)) ? $which : 4; ?>&d=<?php echo (isset($d)) ? $d : null; ?>&dl=<?php echo (isset($dl)) ? $dl : null; ?>";

        jQuery.getJSON($dUrl, function(d){
            // Create a new blank DataTable         
            var data = new google.visualization.DataTable(d);
            // Create our columns
            /*
            data.addColumn('date', 'Date');
            data.addColumn('number', 'Carbs');
            data.addColumn('number', 'Sugar');
            data.addColumn('number', 'Units');
            // Create our Rows
            jQuery.each(d, function(i) {
                data.addRows([d[i].Dates, d[i].Carbs, d[i].Sugar, d[i].Units]);
            }); 
            */      
            var options = {
                'colors': ['red', 'blue', 'yellow'],
                'width': '98%', 
                'height': 280, 
                'backgroundColor': 'none',
                'hAxis': {'textStyle': {fontName: 'Calibri', 
                    fontSize: '12'}},
                'vAxis': {'textStyle': {fontName: 'Calibri', 
                    fontSize: '12'}},
                'legendTextStyle': {fontName: 'Calibri', 
                    fontSize: '12'}
            };
            //var chart = new google.visualization.ColumnChart(document.getElementById('<?php echo $where; ?>'));
            var chart = new google.visualization.ColumnChart(document.getElementById('weekly_chart_div'));
            chart.draw(data, options);

        }).fail(function(msg){console.log('Error pulling in the data.' + msg);});

    }
</script>

Original JSON from the $dUrl : 来自$dUrl原始JSON:

{"cols":[{"id":"Date","label":"Date","type":"string"},
    {"id":"Carbs","label":"Carbs","type":"string"},
    {"id":"Sugar","label":"Sugar","type":"string"},
    {"id":"Units","label":"Units","type":"string"}],
"rows":[["08\/23","40.0000000","256.0000000","9.0000000"],
    ["08\/24","33.8333333","102.5000000","4.6666667"],
    ["08\/25","38.2000000","290.2000000","10.6000000"],
    ["08\/26","36.0000000","322.0000000","12.0000000"],
    ["08\/28","23.6666667","348.3333333","9.6666667"],
    ["08\/29","31.3333333","214.1666667","7.3333333"],
    ["08\/30","16.0000000","154.0000000","4.0000000"]]}

New JSON after Data Retrieval Update: 数据检索更新后的新JSON:

{"cols":[{"id":"Date","label":"Date","type":"string"},
    {"id":"Carbs","label":"Carbs","type":"number"},
    {"id":"Sugar","label":"Sugar","type":"number"},
    {"id":"Units","label":"Units","type":"number"}],
"rows":[{"c":{"v":9}},{"c":{"v":4.6666667}},{"c":{"v":10.6}},{"c":{"v":12}},{"c":{"v":9.6666667}},{"c":{"v":7.3333333}},{"c":{"v":4}}]}

Yes, right now I am getting an error this.J[a].c is undefined , but it only shows where the chart should be loaded...not in FireBug 是的,现在我遇到了一个错误this.J[a].c is undefined ,但它仅显示应在哪里加载图表...不在FireBug中

What I am aiming for is something like this: example: http://o7th.com/Image3.png 我的目标是这样的:示例: http : //o7th.com/Image3.png

Your rows are not formatted correctly. 您的行格式不正确。 Rows is an array of objects, where each object has a "c" (array of cells) and an optional "p" (properties object) parameters. 行是对象的数组,其中每个对象都有一个“ c”(单元格数组)和一个可选的“ p”(属性对象)参数。 The array of cells is an array of objects with "v" (column data type, value of cell) and optional "f" (string, formatted value of cell) and "p" (parameters object) properties. 单元格数组是具有“ v”(列数据类型,单元格的值)以及可选的“ f”(字符串,单元格的格式化值)和“ p”(参数对象)属性的对象的数组。

As an example, your first row of data should look like this: 例如,您的第一行数据应如下所示:

{"c":[{"v":"08\/23"},{"v":40,"f":"40.0000000"},{"v":256,"f":"256.0000000"},{"v":9,"f":"9.0000000"}]}

In order to generate that from a JSON encoded PHP array, the array would have to look like this: 为了从JSON编码的PHP数组生成该数组,该数组必须看起来像这样:

$row = array(
    'c' => array(
        array('v' => '08\/23'),
        array('v' => 40, 'f' => "40.0000000"),
        array('v' => 256, 'f' => "256.0000000"),
        array('v' => 9, 'f' => "9.0000000")
    )
);

By default, MySQL outputs all numbers as strings, so you need to cast them as ints or floats in order for them to be output as numbers, like this: 默认情况下,MySQL将所有数字输出为字符串,因此您需要将它们强制转换为整数或浮点数,以便将它们输出为数字,如下所示:

$foo = '33.333333'; // $foo == '33.333333'
$bar = (int) $foo; // $bar == 33
$cad = (float) $foo; // $cad == 33.333333

You can change or remove the formatted values if you don't want them (they are what will appear in the tooltips of the chart). 如果不希望使用格式化的值,则可以更改或删除这些值(它们将出现在图表的工具提示中)。

Edit: 编辑:

You need to give each cell it's own array in the cells array; 您需要在cells数组中为每个单元格分配自己的数组; try this: 尝试这个:

$rows[] = array(
    'c'=>array(
        array('v'=>$date),
        array('v'=>$CNums[$i]['Carbs']),
        array('v'=>$CNums[$i]['Sugar']),
        array('v'=>$CNums[$i]['Units'])
    )
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM