简体   繁体   English

Google图表:与json约会

[英]Google charts : date with json

I am using google charts and i have a problem to pass the date from php to javascript 我正在使用谷歌图表,我有一个问题,将日期从PHP传递给javascript

I use this : 我用这个:

PHP : PHP:

$dataArray = array();
while ($resultat = $resultats->fetch_array(MYSQLI_ASSOC)) 
$thedate = "(".$year.", ".$month.")";
$fixe = "12";
$variable = "14";
$dataArray[] = array($thedate, (int) $fixe, (int) $variable);

JS : JS:

var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('number', 'Taux fixes');
data.addColumn('number', 'Taux variables');
data.addRows(<?php echo json_encode($dataArray); ?>);

The error is : Uncaught Error: Type mismatch. 错误是:未捕获错误:类型不匹配。 Value (2014, 1) does not match type date in column index 0 值(2014,1)与列索引0中的类型日期不匹配

Does someone know how to send the date ? 有人知道如何发送日期吗? In which format ? 格式是什么? Google charts want a "new Date(2012, 03)" in JS 谷歌图表想在JS中使用“新日期(2012年,03年)”

Thanks. 谢谢。

When using JSON, the proper format for dates is a string like this: 'Date(year, month, day)' (note there is no new keyword used in the string), where month is zero-indexed (so January is 0 not 1 ). 使用JSON时,日期的正确格式是这样的字符串: 'Date(year, month, day)' (注意字符串中没有使用new关键字),其中month为零索引(因此1月为0不是1 )。 The only DataTable construction method that supports inputting dates in this fashion is passing a JSON representation of the DataTable directly to the constructor: 支持以这种方式输入日期的唯一DataTable构造方法是将DataTable的JSON表示直接传递给构造函数:

var data = new google.visualization.DataTable(<?php echo json_encode($dataTable, JSON_NUMERIC_CHECK); ?>);

This requires reconfiguring your PHP a bit to construct a proper DataTable JSON string. 这需要重新配置PHP以构造适当的DataTable JSON字符串。 You need to create an associative array with 'cols' and 'rows' keys. 您需要使用'cols''rows'键创建一个关联数组。 The 'cols' key sets the columns for your DataTable, and the 'rows' key contains the rows of data: 'cols'键设置DataTable的列, 'rows'键包含数据行:

$dataTable = array (
    'cols' => array (
        array('type' => 'date', 'label' => 'Date'),
        array('type' => 'number', 'label' => 'Taux fixes'),
        array('type' => 'number', 'label' => 'Taux variables')
    ),
    'rows' => array()
);
while ($resultat = $resultats->fetch_array(MYSQLI_ASSOC)) {
    // put results in $year, $month, $fixe, $variable

    $month = $month - 1; // correcting for javascript's 0-indexed months
    $dataTable['rows'][] = array('c' => array(
        array('v' => "Date($year, $month, 1)"),
        array('v' => $fixe),
        array('v' => $variable)
    ));
}

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

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