Quick actions

cmd+k|ctrl+k

Navigation

Languages

Example of generating data for multiple line graph using Chartjs

Snippet info

Language

Php

Visibility

public

Author

valdineireis

Created

2020-11-26T20:44:28Z

Updated

2020-11-26T20:46:49Z

<?php

function generateRgb() {
    $rgbColor = array();

    foreach(array('r', 'g', 'b') as $color){
        //Generate a random number between 0 and 255.
        $rgbColor[$color] = mt_rand(0, 255);
    }
    
    return 'rgb('.implode(",", $rgbColor).')';
}

$db = [
    [
        'day' => 1,
        'month' => 10,
        'total' => 10,
        'id' => 1,
        'description' => 'Link 01'
    ],
	[
        'day' => 15,
        'month' => 10,
        'total' => 6,
        'id' => 2,
        'description' => 'Link 02'
    ],
    [
        'day' => 3,
        'month' => 11,
        'total' => 15,
        'id' => 2,
        'description' => 'Link 02'
    ],
    [
        'day' => 3,
        'month' => 11,
        'total' => 9,
        'id' => 1,
        'description' => 'Link 01'
    ],
    [
        'day' => 8,
        'month' => 11,
        'total' => 10,
        'id' => 1,
        'description' => 'Link 01'
    ],
    [
        'day' => 8,
        'month' => 11,
        'total' => 10,
        'id' => 2,
        'description' => 'Link 02'
    ],
];

$elements = [];
$labels = [];

// montar os elementos do dataset
foreach ($db as $link) {
    $link = (object)$link;
    
    if (! key_exists($link->id, $elements)) {
        $rgbColor = generateRgb();
        $elements[$link->id] = [
            'label' => $link->description,
            'fill' => false,
            'borderWidth' => 1,
            'borderColor' => $rgbColor,
            'backgroundColor' => $rgbColor
        ];
    }
    
	// monta os labels
	$keyLabels = $link->day.$link->month;
	if (! key_exists($keyLabels, $labels)) {
        $labels[$keyLabels] = $link->day.'/'.$link->month;
	}
}

// montar os dados de cada dataset
foreach ($elements as $key => $element) {
    $element = (object)$elements[$key];
    $data = [];
    
    foreach ($db as $link) {
        $link = (object)$link;
        
		$keyData = $link->day.$link->month;
        if ($key === $link->id) {
            $data[$keyData] = $link->total;
        } else if (key_exists($keyData, $data)) {
            continue;
        } else {
            $data[$keyData] = 0;
        }
    }
    
    $elements[$key]['data'] = array_values($data);
}

$result = ['datasets' => array_values($elements), 'labels' => array_values($labels)];

echo json_encode( $result );
INFO