rosey85uk rosey85uk - 5 months ago 7x
MySQL Question

Generate PHP Array to mimic JSON format

im a bit rusty with PHP and need some advice/help.

I am trying to generate a rough and quick api that returns some JSON data to populate a JavaScript chart. I am using PHP to query the Database. I can retrieve the stats per month/year, however I am struggling on a way to generate the PHP array prior to using JSON_ENCODE().

The format I am trying to get is:

y: 'January',
a: 150,
b: 90,
c: 50
}, {
y: 'February',
a: 75,
b: 65,
c: 50
}, {
y: 'March',
a: 50,
b: 40,
c: 50
}, {
y: 'April',
a: 75,
b: 65,
c: 50

and so on..through to December. a = 2014 / b = 2015 / c = 2016.

I have a DB query which takes a
parameter and it returns a count of records.

My initial thought was to use three arrays:

$months = array("January","February","March","April","May","June","July","August","September","October","November","December");
$years = array("2014","2015","2016");
$yearlabels = array("a","b","c");

However I cant see how I can do this to return an array in the format I want.

Any ideas?


You can try

$out = [];

foreach($months as $month) {
   $arr = array();
   $arr['y'] = $month;
   foreach($yearlabels as $label) {
      $arr[$label] = '2';
   $out[] = $arr;

echo json_encode($out);

I hope this will help you. If not then let me know.