如何 return JSON 从 MySQL table 在 PHP 中以以下格式响应

How to return JSON response in below format from MySQL table in PHP

在我的数据库中 table 我在日期列中以 2015-03-22 这样的格式存储日期。

|   mydate   |
------------
| 2015-03-22 |
| 2015-03-17 |
| 2015-04-02 |
| 2015-04-01 |

我需要 JSON 到 return 这样的回复:

    {  
   "result": [{    
     "2014":[{}],
     "2015":[{
        "April":[
            "2015-04-05",
            "2015-04-04",
            "2015-04-03",
            "2015-04-01"
        ],
        "March":[
            "2015-03-25",
            "2015-03-14",
            "2015-03-07",
            "2015-03-01"
        ]
     }] 
   }]    
}

我试过这个查询,但是我没有像上面那样创建 JSON 个对象:

$getDate = "SELECT DISTINCT( mydate), MONTHNAME( mydate ) AS m, YEAR( mydate ) as y 
FROM table_name 
GROUP BY m, mydate  ORDER BY mydate DESC";

您需要顺序定义嵌套数组:

$sql = "SELECT
    DISTINCT( mydate) AS `date`,
    MONTHNAME( mydate ) AS m,
    YEAR( mydate ) as y
FROM
    table_name
GROUP BY
    m, mydate
ORDER BY
    mydate DESC";

$result = mysqli_query($c, $sql);

$structure = array();
while ($row = mysqli_fetch_assoc($result))
{
    //year
    if(!isset($structure[$row['y']]))
    {
        $structure[$row['y']] = array();
    }

    //month inside the year
    if(!isset($structure[$row['y']][$row['m']]))
    {
        $structure[$row['y']][$row['m']] = array();
    }

    //date inside the month
    $structure[$row['y']][$row['m']][] = $row['date'];
}
mysqli_free_result($result);

//encode to json
$structure = array('result' => $structure);
$json = json_encode($structure);