Chartjs-Adding a for loop/foreach loop for Charts.js

4👍

You can create your dataset array in your PHP code and pass it to the JS as json. You will then simply need to parse it before using.

In PHP:

$datasets = [
    [
        'label'=>'',
        'fillColor'=> 'rgba(220,220,220,0.2)',
        'strokeColor'=> 'rgba(220,220,220,1)',
        'pointColor'=> 'rgba(220,220,220,1)',
        'pointStrokeColor'=> '#fff',
        'pointHighlightFill'=> '#fff',
        'pointHighlightStroke'=> 'rgba(220,220,220,1)',
        'data' => [1,2,3]
    ],
    [
        'label'=>'',
        'fillColor'=> 'rgba(220,220,220,0.2)',
        'strokeColor'=> 'rgba(220,220,220,1)',
        'pointColor'=> 'rgba(220,220,220,1)',
        'pointStrokeColor'=> '#fff',
        'pointHighlightFill'=> '#fff',
        'pointHighlightStroke'=> 'rgba(220,220,220,1)',
        'data' => [1,2,3]
    ]
];
$datasets = json_encode($datasets);

In JS:

var data = {
    labels: {!! json_encode($month_array) !!},
    datasets: JSON.parse('<?=$datasets?>')
};

BTW I think it’s worth mentioning that a JS array is not treated the same way as a JSON string, even though they look pretty similar. So, even though I haven’t seen much details of the implementation, I assume that you need to pass an array instead of JSON as value for labels. You can use the same approach as with the datasets here as well.

Leave a comment