1๐
โ
My error was in another part of code, related to the arrays. I will post the right solution:
<?= ChartJs::widget([
'type' => 'line',
'options' => [
'height' => 400,
'width' => 800,
],
'data' => [
'labels' => $labels,
'datasets' => [
[
'label' => "2018",
'backgroundColor' => "rgba(255,99,132,0.2)",
'borderColor' => "rgba(255,99,132,1)",
'pointBackgroundColor' => "rgba(255,99,132,1)",
'pointBorderColor' => "#fff",
'pointHoverBackgroundColor' => "#fff",
'pointHoverBorderColor' => "rgba(255,99,132,1)",
'data' => $data,
],
]
]
]); ?>
This is the PHP to get current week data:
$labels = array();
$data = array();
$curweek = date('Y-m-d', strtotime("previous monday"));
$today = date('Y-m-d');
$dates = new DatePeriod(
DateTime::createFromFormat('Y-m-d|', $curweek),
new DateInterval('P1D'),
DateTime::createFromFormat('Y-m-d|', $today)->add(new DateInterval('P1D'))
);
foreach ($dates as $date) {
$datestr = $date->format('Y-m-d');
$index = array_search($datestr, array_column($chartvalue, 'dataNl'));
if ($index === false) {
$labels[] = date("d", strtotime($datestr));
$data[] = 0;
} else {
$labels[] = date("d", strtotime($datestr));
$data[] = $chartvalue[$index]['totale'];
}
}
1๐
I used to do it like this:
var ctx = document.getElementById("Chart1"); // the element where the chart should be rendered
var myChart1 = new Chart(ctx, {
type: 'line',
data: {
labels: [<?php
foreach( $m as $key => $row) {
echo "'".$row['label']."', "; // you can also use $row if you don't use keys
}
} ?>],
datasets: [{
label: '2018',
data: [<?php
foreach( $t as $key => $row) {
echo "'".$row['data']."', "; // you can also use $row if you don't use keys
} ?>],
backgroundColor => "rgba(255,99,132,0.2)",
borderColor => "rgba(255,99,132,1)",
pointBackgroundColor => "rgba(255,99,132,1)",
pointBorderColor => "#fff",
pointHoverBackgroundColor => "#fff",
pointHoverBorderColor => "rgba(255,99,132,1)",
}]
},
options => [
'height' => 400,
'width' => 800,
]
});
I create the chart with javascript and add data from inside my php array.
You can display the chart by adding a element with the above ID.
PHP is used to process data and JS to display data.
So use JS to display the chart and PHP to process data.
In your case you can just do this:
<?php
$data = array(foreach( $t as $key => $row) {
echo "'".$row['data']."', "; // you can also use $row if you don't use keys
});
$labels = array(foreach( $m as $key => $row) {
echo "'".$row['label']."', "; // you can also use $row if you don't use keys
});
?>
<?= ChartJs::widget([
'type' => 'line',
'options' => [
'height' => 400,
'width' => 800,
],
'data' => [
'labels' => $labels,
'datasets' => [
[
'label' => "2018",
'backgroundColor' => "rgba(255,99,132,0.2)",
'borderColor' => "rgba(255,99,132,1)",
'pointBackgroundColor' => "rgba(255,99,132,1)",
'pointBorderColor' => "#fff",
'pointHoverBackgroundColor' => "#fff",
'pointHoverBorderColor' => "rgba(255,99,132,1)",
'data' => $data
],
]
]
]); ?>
Source:stackexchange.com