1👍
✅
What you want is to create an array of objects, then use json_encode
and it should produce what you need. Try this:
$array = array();
$dataset = new stdClass;
$dataset->label = "My first dataset";
// repeat for each field
$array[] = $dataset;
echo json_encode($array);
What we can do to shorten this is rather than declare a new dataset each time we can use an array and typecast it to an object like this:
$datasets = array();
$datasets[] = (object) array(
'label' => "My First dataset",
'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' => [65, 59, 80, 81, 56, 55, 40]
);
Check out this eval.in for a working example.
Update
For your complete structure you need:
$data = (object) [
'labels' => ["January", "February", "March", "April", "May", "June", "July"],
datasets => []
];
$data->datasets[] = (object) [
'label' => "My First dataset",
'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' => [65, 59, 80, 81, 56, 55, 40]
];
echo json_encode($data);
Source:stackexchange.com