Home:ALL Converter>PHP encoding nested array as object

PHP encoding nested array as object

Ask Time:2016-11-10T23:12:42         Author:celsomtrindade

Json Formatter

I'm trying to get a list of year and month from PHP to my web site page. The website works with JavaScript, so I need this data to be JSON.

There is no problem to generate the information I need, but I use json_encode on the PHP, all the nested arrays turn into object and because of this, I can't have the proper behavior on the JavaScript.

This is what I'm doing to generate the array on the PHP:

$list = sql("SELECT DISTINCT YEAR(created) AS year FROM order");

foreach ($list as &$row) {
    $row['month'] = array();

    for ($i=1; $i<=12; $i++) {
        $row['month'][$i] = new stdClass();
        $row['month'][$i]->Month = date("M", strtotime(date("Y")."-".$i."-01"));

        //more information goes here...
    }
}

If I just print the $list using return print_r($list); this is the result:

Array (
    [0] => Array (
        [year] => 2016
        [month] => Array (
            [1] => stdClass Object (
                [Month] => Jan
            )
            [2] => stdClass Object (
                [Month] => Feb
            )
            //Etc...

But when I use

return print_r(json_encode($list));
//or
return print_r(json_encode($list, true));

All the nested array turn into object. For example, the Month array, turn into an object, this is a print screen of the console.log of the result:

enter image description here

Is there a way to fix this? Or am I doing wrong?

Author:celsomtrindade,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/40530926/php-encoding-nested-array-as-object
yy