Using associative PHP array in JS to later on use in chart generated via chart.js

đź‘Ť:0

You can build the correct structure in javascript itself, like so

// it's not good to rely on reverse() because we are using an ASSOCIATIVE array
// so we get the object's keys and sort them
var labels = Object.keys(input).sort(function (a, b) {
    // the substring removes the 'SEASON ' part
    // i.e. we sort by the numeric part
    return a.substring(7) - b.substring(7);
});
// pick the buff elements in the same order as the labels
var buffseason = labels.map(function (e) {
    return input[e].buff;
});
// pick the buff elements in the same order as the labels
var nerfseason = labels.map(function (e) {
    return input[e].nerf;
})

var lineData = {
    ...

where input is your JSON encoded associative array, i.e. something like

{
    'SEASON 3': {
        'nerf': 0,
        'buff': 2
    },
    'SEASON 2': {
        'nerf': 5,
        'buff': 2
    },
    'SEASON 1': {
        'nerf': 9,
        'buff': 20
    }
}

Leave a comment