MySQL的基本JSON输出

时间:2014-02-17 18:52:07

标签: php mysql json

如何修改我的代码MySQL以输出此JSON数据:

{
"Monday": [
    {
        "title": "Title 1 goes here",
        "details": "Lesson Details here...."
    },
    {
        "title": "Title 2 goes here",
        "details": "Lesson Details here..."
    }
],
"Tuesday": [
    {
        "title": "Title 3 goes here",
        "details": "Lesson Details here..."
    },
    {
        "title": "Title 4 goes here",
        "details": "Lesson Details here..."
    }
],
"Wednesday": [
    {
        "title": "Title 5 goes here",
        "details": "Lesson Details here..."
    },
    {
        "title": "Title 6 goes here",
        "details": "Lesson Details here..."
    }
]

}

MySQL代码如下: 我正在使用数据库中的视图来输出课程天数,每天都有很多课程。

            $query = "SELECT * FROM LessonsView";
        $resultset = mysql_query($query, $connection);
        $records = array();

        //Loop through all our records and add them to our array
        while($r = mysql_fetch_assoc($resultset))
        {
            $records['LessonsData'][] = $r; 
        }

        //Output the data as JSON
        header('Content-type: application/json');
        echo json_encode($records);
    }
}

我很感谢你帮助我的代码,因为我是MYSQL的新手。 感谢。

1 个答案:

答案 0 :(得分:0)

SELECT * FROM LessonsView

这完全取决于数据库中的列。您可以拥有标题和详细信息列。我假设你有一些专栏来存放工作日的某个地方。

查看GROUP BY

SELECT Weekday, title, details FROM LessonsView GROUP BY Weekday, title, details