Create an array of Google Chart data tables from two arrays

I am trying to use the google api chart: https://google-developers.appspot.com/chart/interactive/docs/gallery/columnchart

I have two arrays that I would like to use to create and mark visualizations. However, I cannot find a way to combine and convert these arrays into the correct structure of objects.

My arrays are as follows and their contents are next to them:

years; // 2014,2015,2020,2021 sales; // 100,100,200,100 

I need to dynamically use these arrays to create this object, which is used in a format that uses the Google API:

  var data = google.visualization.arrayToDataTable([ ['Year', 'Sales'], ['2014', 100], ['2015', 100], ['2020', 200], ['2021', 100] ]); 

Thanks for any help.

+7
source share
2 answers

You must use addColumn and addRow in a for loop to go through your arrays.

Here is an example:

 function drawVisualization() { // Create and populate the data table. var years = ['2001', '2002', '2003', '2004', '2005']; var sales = [1, 2, 3, 4, 5]; var data = new google.visualization.DataTable(); data.addColumn('string', 'years'); data.addColumn('number', 'sales'); for(i = 0; i < years.length; i++) data.addRow([years[i], sales[i]]); // Create and draw the visualization. new google.visualization.LineChart(document.getElementById('visualization')). draw(data, {}); } 
+18
source

Below is the complete code with shared data filling.

 <?php function testing($chartId, $chartFunc, $chartTitle, $xAxisTitle, $chartData, $chartType) { $pageMeat =<<<EOD <html> <head> <script type="text/javascript" src="https://www.google.com/jsapi"></script> <script type="text/javascript"> google.load("visualization", "1", {packages:["corechart"]}); google.setOnLoadCallback($chartFunc); function $chartFunc() { var data = google.visualization.arrayToDataTable($chartData); var options = { title: '$chartTitle', hAxis: {title: '$xAxisTitle', titleTextStyle: {color: 'red'}} }; EOD; if($chartType == "line") { $pageMeat .=<<<EOD var chart = new google.visualization.LineChart(document.getElementById('$chartId')); EOD; } else if($chartType == "pie") { $pageMeat .=<<<EOD var chart = new google.visualization.PieChart(document.getElementById('$chartId')); EOD; } else { $pageMeat .=<<<EOD var chart = new google.visualization.ColumnChart(document.getElementById('$chartId')); EOD; } $pageMeat .=<<<EOD chart.draw(data, options); } </script> </head> <body> <div id="$chartId" style="width: 900px; height: 500px;"></div> </body> </html> EOD; echo $pageMeat; } $gChartId = "vertColumns"; $gChartFn = "columnChart"; $gChartTitle = "Company Performance"; $gXAxisTitle = "Year"; $gChartData[] = array('Year', 'Sales', 'Expenses'); $gChartData[] = array('2004', 1000, 400); $gChartData[] = array('2005', 1170, 460); $gChartData[] = array('2006', 660, 1120); $gChartData[] = array('2007', 1030, 540); testing($gChartId, $gChartFn, $gChartTitle, $gXAxisTitle, json_encode($gChartData), "column"); ?> 
0
source

All Articles