问题
I am currently using Highcharts in symfony. It works good when I enter static data (array1/array2/array3/array4) like this:
$ob1 = new Highchart();
$ob1->chart->renderTo('barchart');
$ob1->title->text('Chart 1');
$ob1->xAxis->categories($arrayResult);
$ob1->plotOptions->pie(array(
'allowPointSelect' => true,
'cursor' => 'pointer',
'dataLabels' => array('enabled' => false),
'showInLegend' => true
));
$ob1->series(array(array('type' => 'column','name' => 'bar1', 'data' => $array1),
(array('type' => 'column','name' => 'bar2', 'data' => $array2)),
(array('type' => 'column','name' => 'bar3', 'data' => $array3)),
(array('type' => 'column','name' => 'bar4', 'data' => $array4))
));
but what I need is to enter data within a loop because I have an irregular number of arrays. I tried this but I got an error "unexpected 'while' (T_WHILE)" Is there anything I have missed here?
Here is my code using while to add Chart's Data Series:
$i=1;
$number=4;
$ob1->series(array(
(
$myarray = array();
while($i <= $number): array_push($myarray, array(0 => 'value', 1=> $i));
$i++;
array('type' => 'column','name' => 'bar'.$i, 'data' => $myarray)
endwhile;
),
));
I also tried this and displays only the last iteration of the while
$i=1;
$number=4;
$myarray = array();
while($i <= $number):
array_push($myarray, array(0 => 'value', 1=> $i));
$i++;
$ob1->series(array (array('type' => 'column','name' => 'bar'.$i, 'data' => $myarray)));
endwhile;
回答1:
Your php statement is not valid, has invalid syntax. To avoid this type of error, never create a loop inside the function argument. Simplify your syntax and use temporal variables, is easy to read and to understand what are you doing, remember, every good developer always say: "divide and conquer" :)
$i = 1;
$number = 4;
$chartData = [];
while ($i <= $number) {
$chartData[] = [
'type' => 'column',
'name' => 'bar'.$i,
'data' => [
'value',
$i,
],
];
$i++;
}
$ob1->series($chartData);
来源:https://stackoverflow.com/questions/43891514/draw-charts-with-a-loop-using-highcharts-in-symfony