Use MySQL data as the chart data for the cakephp highchart plugin

398 Views Asked by At

I would like to use the highchart plugin in cakephp. I installed it and I can run all the demos that come with the plugin. I would like to use it in my own controller and took one of the examples as an implementation guide.
If I have the following code in my controller it does NOT work, i.e. highchart does not display any of the input values.

    $resultStatistics = $this->Statistic->find("all", $params = array(  'fields' => 'new_students_total','recursive'    =>  -1) );
    $chartData1 = array();
    $chartData1 = Hash::extract($resultStatistics, '{n}.Statistic.new_students_total');

//  $chartData1 = array(0=>5, 1=>5, 2=>4, 3=>4);    
    $this->print_r2($chartData1);

    $chartName = 'Evolution of Actual Number of Students';
    $mychart = $this->Highcharts->create($chartName, 'line');

    $this->Highcharts->setChartParams($chartName, array(
                    'renderTo'              => 'linewrapper', // div to display chart inside
                    'chartWidth'            => 600,
                    'chartHeight'           => 500,
                    'chartMarginTop'        => 60,
                    'chartMarginLeft'       => 90,
                    'xAxisCategories'       => array('Jan', 'Feb', 'Mar', 'Apr'),


                    // autostep options
                 //   'enableAutoStep'      => TRUE
                        )
                );
    $series1 = $this->Highcharts->addChartSeries();
    $series1->addName('ABC')
            ->addData($chartData1);

    $mychart->addSeries($series1);
    $this->set(compact('chartName'));   

The result from the database query is a simple array with 4 integer values.

But if I uncomment the line 4, “$chartData1 = array(0=>5, 1=>5, 2=>4, 3=>4);”, basically defining the values of the array manually it DOES WORK and a linechart is drawn. I use Cakephp 2.4.3 and PHP 5.6 I can't seem to figure out the difference between the "mysql" version of the array $chartData1 and the "manual defined" version of $chartData1. What am I missing?

1

There are 1 best solutions below

0
On

After lots of checking I eventually found the problem. The Cake plug in helper expects integer (or reals) in the chartData1 array. So simple adding the following lines:

foreach ($resultStatistics as $result) {
    $chartData[] = (int) $result['Statistic']['new_students_total'];  
}

at last solved my problem. Thank anyway for your help