Reputation: 3064
I have created the following string in PHP
["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)"]
and want the same to use in Google Chart data
The above string I have grabbed in a JavaScript variable (str_data
) and tried like this
var data = google.visualization.arrayToDataTable([str_data]);
but getting the following error:
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 code) The following code runs inside a loop and creates one row at a time.
$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 . ', ""],';
}
Upvotes: 1
Views: 345
Reputation: 61230
instead of trying to pass json as a string
build the json in php, then pass the encoded json as a string
// 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);
then, assuming you're using ajax to get the data, set the type to json...
$.ajax({
url: '...',
dataType: 'json'
}).done(...
Upvotes: 1