Chartjs-How to populate my chartjs piechart dynamically

0๐Ÿ‘

I think you are stuck at to create Piedata for the chart form JSON. Here is the Solution:

Your JSON string:

$json = '[{"clinic_name":"Clinic 1","total_checked_up":"4"},{"clinic_name":"Clinic 2","total_checked_up":"0"},{"clinic_name":"Clinic 3","total_checked_up":"0"},{"clinic_name":"Clinic 4","total_checked_up":"0"}]';

First Convert it to array:

$array = json_decode($json);

Declare the Empty variable:

$string_array = '';

Loop Threw the Array:

foreach($array as $single_array){

    $string_array[] = array(
    'value'=>$single_array->total_checked_up,
    'color'=>'#f56954',
    'highlight'=>'#f56954',
    'label'=>$single_array->clinic_name
    );  
}

Convert the array into JSON again to get your desired PieData:

var PieData  = json_encode($string_array);

This is how your PieData data look like.

[
    {
        "value": "4",
        "color": "#f56954",
        "highlight": "#f56954",
        "label": "Clinic 1"
    },
    {
        "value": "0",
        "color": "#f56954",
        "highlight": "#f56954",
        "label": "Clinic 2"
    },
    {
        "value": "0",
        "color": "#f56954",
        "highlight": "#f56954",
        "label": "Clinic 3"
    },
    {
        "value": "0",
        "color": "#f56954",
        "highlight": "#f56954",
        "label": "Clinic 4"
    }
]

Leave a comment