0

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 $year and $month 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?

1
  • Why not make the array with the desired format straight from the start, something like: $array = [ [ "y" => "January", "a" => numA, "b" => "numB", "c" => "numC" ], [....]] and then json_encode($array) Commented May 24, 2016 at 11:26

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Hi Shalu, thanks. This worked perfectly with a few tweaks :) knew I was over complicating things!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.