Php – Google Visualization API – Multi-Line Chart

google-visualizationlinechartPHP

I've an array created after pulling records from the database. The array is like:

// $xyz array
Array
(
    [f30] => Array
        (
            [December 2012] => 71
            [November 2012] => 70
            [October 2012] => 66
        )    

    [f32] => Array
        (
            [December 2012] => 85
            [November 2012] => 83
            [October 2012] => 81
        )
)

If it were a single line chart, I'm able to plot it effortlessly. However, when I try to plot a multi-line chart, I'm running into a lot of problems. Below is the code that I'm attempting to plot the data with:

PHP

$table = array();
$table['cols'] = array(
           array('label' => 'Month', 'type' => 'string')        
         );

$rows = array();
foreach($xyz as $form=>$hhh)
{        
   $table['cols'][] = array('label'=>$form, 'type'=>'number');
   foreach($hhh as $mnth=>$pt)
   {
      $temp = array();
      $temp[] = array('v' => (string) $mnth);
      $temp[] = array('v' => (int) $pt);
      $rows[] = array('c'=>$temp);
    }
}

$table['rows'] = $rows;
$jsonTable = json_encode($table);

JS

<script type="text/javascript">

    google.load('visualization', '1', {'packages':['corechart']});    
    google.setOnLoadCallback(drawChart);
    function drawChart() {
      var data = new google.visualization.DataTable(<?=$jsonTable?>);
      var options = {
           title: 'Some title',
          is3D: 'true',
          width: 800,
          height: 600
        };            
      var chart = new google.visualization.LineChart(document.getElementById('divID'));
      chart.draw(data, options);
    }
    </script>

I've tried various permutations and combinations by changing the positions of $temp, $rows and $table['rows'] arrays, but I can't seem to plot two lines in a single graph. I'm probably messing up the placement of the arrays.

The closest I managed to get was like the one below:

What I got

But my expected output is something like
What I'm looking for

f30 and f31 go in place of Sales and Expenses and October, November, and December go in place of 2004, 2005, 2006, 2007

Best Answer

I figured it out myself. My god! What a relief it is. I just had to have an array in this format:

Array
(
    [December 2012] => Array
        (
            [0] => 71
            [1] => 85
        )

    [November 2012] => Array
        (
            [0] => 70
            [1] => 83                
        )

    [October 2012] => Array
        (
            [0] => 66
            [1] => 81
        )

)

The rest was a small modification in the foreach loop and voila! It was done.

Related Topic