How to divide series in php to create a json table for google charts How to divide series in php to create a json table for google charts json json

How to divide series in php to create a json table for google charts


the data format for google's line chart,
calls for the x-axis to be the first column in the data table.
each additional column is considered a series.

in order to have a series for each test (string),
the data table would need to be in the following format.

diameter  |  AAAAAAAAA  |  BBBBBBBBB  |  CCCCCCCCC--------  |  ---------  |  ---------  |  ---------20        |  12         |             |           10        |  19         |             |           7         |  72         |             |           21        |             |  15         |           12        |             |  52         |           3         |             |  65         |           19        |             |             |  44       11        |             |             |  22        5         |             |             |  36       

this may be difficult to build in your query / php,
especially if there are many more series for test (string).

as such, you can leave the php alone,
and use google's DataView class,
to transform the data into the format you need.

// create data viewvar view = new google.visualization.DataView(data);

the DataView class allows you to provide your own columns, using method --> setColumns(array)

pass an array of the columns you need.
we can pass the column index to use an existing column.
such as 1 for the 'diameter' column.

// init view columns, use diameter as x-axisvar viewColumns = [1];

or we can pass an object {} to use as a calculated column.
the object should have the normal column properties,
such label & type.

it can also have a calc function, which is run for each row in the data table.
it receives the data table and row index as arguments.
the function should return the value for that column.

// build view column for each test seriesdata.getDistinctValues(0).forEach(function (test, index) {  // add y-axis column for test  viewColumns.push({    calc: function (dt, row) {      // return value for test (string)      if (dt.getValue(row, 0) === test) {        return dt.getValue(row, 2);      }      // return null if row does not equal test (string)      return null;    },    label: test,    type: 'number'  });});

in order to build a column for each unique test (string),
use data table method --> getDistinctValues(columnIndex)
this will return an array of the unique values for the given column.


see following working snippet...