BN83
BN83

Reputation: 912

Getting PHP multidimensional array in to Javascript using JSON?

I need to get an array to display the following way:

var categories = data.categories;

for(a = 0; a < data.count; a++){
    var names[a] = data.name[a];
    var values[a] = data.value[a];
}

There will be one "Categories" array, for example "May 2017","June 2017","July 2017","August 2017","September 2017". Then there may be 3/4 arrays containing "Name" and "Values" and I want these to loop through a loop to loop and assign these to variables.

At the moment I'm getting 'Undefined" in all variables.

My output in php is currently:

[
    [{
        "name": "Leads",
        "data": [524, 419, 502, 598, 873],
        "color": "#00afef"
    }, {
        "name": "Purchases",
        "data": [37, 18, 32, 36, 44],
        "color": "#f00"
    }], {
        "categories": ["May 2017", "June 2017", "July 2017", "August 2017", "September 2017"]
    }
]

Upvotes: 0

Views: 41

Answers (1)

Kevin Raoofi
Kevin Raoofi

Reputation: 1033

The JSON you're getting back has horrible schema and you're doing weird things in JS. Hopefully the following will get you back on track:

var data = [
  [{
    "name": "Leads",
    "data": [524, 419, 502, 598, 873],
    "color": "#00afef"
  }, {
    "name": "Purchases",
    "data": [37, 18, 32, 36, 44],
    "color": "#f00"
  }], {
    "categories": ["May 2017", "June 2017", "July 2017", "August 2017", "September 2017"]
  }
];

var categories = data[1].categories;

var names = [];
var values = [];

for (var a = 0; a < data[0].length; a++) {
  names.push(data[0][a].name);
  values.push(data[0][a]);
}

console.log(categories);
console.log(names);
console.log(values);

Upvotes: 1

Related Questions