duanmao2650 2014-08-04 15:57
浏览 32
已采纳

为柱形图创建动态数据表(未知的列和行)

I'm looking for a loop that retrieves the data from the MySQL result set with an unknown amount of columns and rows and puts it in GViz format. With the following code I can read the data dynamically, but I can't get it into the format that Google Visualization API desires:

$cols = array();
$row = array();
$i = 0;
while ($i < mysql_num_fields($result)) {
$meta = mysql_fetch_field($result, $i);
    if (!$meta) {
    echo "No information available<br />
";
    }

    $cols[]= "{id: '".$i."', label: '".$meta->name."', type: '".$meta->type."'}";
    $i++;
    }

while($r = mysql_fetch_assoc($result)) {
$row[]= $r;
}

$jsonTable = json_encode($cols);
$jsonTable2 = json_encode($row);
$Table3 = "{cols: {$jsonTable}, rows: $jsonTable2}";

echo $jsonTable;
     echo '<br>';

echo $jsonTable2;
     echo '<br>';

echo $Table3;
     echo '<br>';

The JS error I get from the browser in debug-mode is:

Error: Invalid type, {[id= '0', label= 'mon', type= 'string']}, for column "0".

I have looked at the data parameter on googles documentation, but their data is hard coded as always. And this SO-page does not generate the cols and rows dynamically.

I'm glad for any help on getting the data parameter right. Thanks!

  • 写回答

1条回答 默认 最新

  • douya7282 2014-08-05 13:02
    关注

    The cause of the error you see is that your JSON string construction is wrong. Don't try to build them yourself, it is much easier to build arrays in PHP and allow the json_encode function to take care of the hard parts for you.

    You can parse your data from MySQL into a DataTable like this:

    $data = array(
        'cols' => array(),
        'rows' => array()
    );
    for ($i = 0; $i < mysql_num_fields($result), $i++) {
        $meta = mysql_fetch_field($result, $i);
        if (!$meta) {
            echo "No information available<br />
    ";
        }
        $data['cols'][] = array(
            'type' => ($i == 0) ? 'string' : 'number',
            'label' => $meta->name,
            'id' => $i
        );
    }
    while($r = mysql_fetch_assoc($result)) {
        $temp = array();
        foreach ($data['cols'] as $col) {
            $temp[] = array('v' => $r[$col['label']]);
        }
        $data['rows'][] = array('c' => $temp);
    }
    echo json_encode($data, JSON_NUMERIC_CHECK);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求
  • ¥20 antv g6 折线边如何变为钝角
  • ¥30 如何在Matlab或Python中 设置饼图的高度
  • ¥15 nginx中的CORS策略应该如何配置
  • ¥30 信号与系统实验:采样定理分析