首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >谷歌图表google.visualization.arrayToDataTable:如何传递格式化字符串

谷歌图表google.visualization.arrayToDataTable:如何传递格式化字符串
EN

Stack Overflow用户
提问于 2019-11-18 21:36:22
回答 1查看 256关注 0票数 1

我在PHP中创建了以下字符串

代码语言:javascript
复制
["Month", "Points", {role: "style"}, "Goal", {role: "annotation"}],
["JAN", 3, "#4a7dae", 6.5, ""],
["FEB", 2, "#4a7dae", 6.5, ""],
["MAR", 3, "#4a7dae", 6.5, ""],
["APR", 1, "#4a7dae", 6.5, ""],
["MAY", 2, "#4a7dae", 6.5, ""],
["JUN", 1, "#4a7dae", 6.5, "Goal (6.5)"]

并希望在Google Chart数据中使用相同的方法

我在JavaScript变量(str_data)中获取了上面的字符串,并尝试如下所示

var data = google.visualization.arrayToDataTable([str_data]);

但得到以下错误:

代码语言:javascript
复制
jsapi_compiled_default_module.js:23 Uncaught (in promise) Error: First row is not an array.
    at gvjs_rba (jsapi_compiled_default_module.js:23)
    at Object.gvjs_Tl [as arrayToDataTable] (jsapi_compiled_default_module.js:25)
    at prev_year_chart_callback_function (evd-all.js?ver=1.0:212)

UPDATE (PHP代码)以下代码在循环内运行,一次创建一行。

代码语言:javascript
复制
$model_str = '["Month", "Points", {role: "style"}, "Goal", {role: "annotation"}],';
if ( $row_index === count( $assoc_array ) - 1 ) {
    $model_str .= '["' . $unix_month_start_formatted . '", ' . $assoc_array[ $key ] . ', "#4a7dae", ' . $prior_season_goal_point . ', "Goal (' . $prior_season_goal_point . ')"],';
} else {
    $model_str .= '["' . $unix_month_start_formatted . '", ' . $assoc_array[ $key ] . ', "#4a7dae", ' . $prior_season_goal_point . ', ""],';
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-11-18 22:07:32

而不是尝试将json作为字符串传递。

在php中构建json,然后将编码后的json作为字符串传递。

代码语言:javascript
复制
// create column headings
$model_str = [];
$columns = [];
$columns[] = "Month";
$columns[] = "Points";
$columns[] = ["role" => "style"];
$columns[] = "Goal";
$columns[] = ["role" => "annotation"];
$model_str[] = $columns;


// create rows
$row = [];
if ( $row_index === count( $assoc_array ) - 1 ) {
    $row[] = $unix_month_start_formatted;
    $row[] = $assoc_array[$key];
    $row[] = "#4a7dae";
    $row[] = $prior_season_goal_point;
    $row[] = "Goal (" . $prior_season_goal_point . ")";
} else {
    $row[] = $unix_month_start_formatted;
    $row[] = $assoc_array[$key];
    $row[] = "#4a7dae";
    $row[] = $prior_season_goal_point;
    $row[] = "";
}
$model_str[] = $row;

// return json
echo json_encode($model_str);

然后,假设您正在使用ajax获取数据,将type设置为json…

代码语言:javascript
复制
$.ajax({
  url: '...',
  dataType: 'json'
}).done(...
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58915846

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档