简体   繁体   中英

JSON getting data from multidimensional arrays

I have been populating a chart embed with data from a multidimensional PHP array ($result). When printing the array to JSON (using print json_encode($result, JSON_NUMERIC_CHECK);) i got the following array structure:

[
  {
  "name":"Array1",
  "data":[
    1,
    2,
    3
  ]
  },
  {
  "name":"Array2",
  "data":[
    1,
    2,
    3
  ]
  }
]

I used this array to populate my highcharts in the code below. This used to work just fine but after I changed the setup of my array it will now have to be reworked.

$.getJSON("../data.php", {id: escape(tableName)}, function(json) {
    chartOptions.chart1.xAxis.categories = json[0]['data'];
    chartOptions.chart1.series[0].data = json[1]['data'];
});

The new setup of my $result array after making some changes is the below:

{
  "Array1":{
    "data":[
      "1",
      "2",
      "3"
    ]
  },
  "Array2":{
    "data":[
      "1",
      "2",
      "3"
    ]
  }
}

As such, the code I used to populate my Highcharts no longer works. I would very much appreciate if anyone can help me understand how I can rework the $.getJSON code such that it would work with the new array structure. Or maybe inform me if I have to stick with the old array setup? Thanks.

From what I can tell (haven't tested), you just need to change:

$.getJSON("../data.php", {id: escape(tableName)}, function(json) {
    chartOptions.chart1.xAxis.categories = json[0]['data'];
    chartOptions.chart1.series[0].data = json[1]['data'];
});

To

$.getJSON("../data.php", {id: escape(tableName)}, function(json) {
    chartOptions.chart1.xAxis.categories = json['Array1']['data'];
    chartOptions.chart1.series[0].data = json['Array2']['data'];
});

The change in the JSON structure changed from an array of dictionaries, to a dictionary of dictionaries, so you no longer access it via index, instead you access it by key (Array1, Array2).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM