首頁 >資料庫 >mysql教程 >如何從 MySQL 資料庫建立 JSON 數組以在 FullCalendar 中動態顯示事件?

如何從 MySQL 資料庫建立 JSON 數組以在 FullCalendar 中動態顯示事件?

Linda Hamilton
Linda Hamilton原創
2024-11-15 05:45:02633瀏覽

How to Build JSON Arrays from MySQL Databases for Dynamic Event Display in FullCalendar?

Building JSON Arrays from MySQL Databases

Many applications require the ability to dynamically create JSON arrays from database records. This is a particularly common task when working with web applications that use frontend frameworks like FullCalendar for displaying dynamic events.

JSON Array Structure

In this specific case, the required JSON array must follow a specific structure:

[
    {
        'id': 111,
        'title': "Event1",
        'start': "2023-08-10",
        'url': "http://yahoo.com/"
    },
    {
        'id': 222,
        'title': "Event2",
        'start': "2023-08-20",
        'end': "2023-08-22",
        'url': "http://yahoo.com/"
    }
]

Database Connection and Data Retrieval

To retrieve the necessary data from the MySQL database, we can use a simple query statement like the following:

SELECT * FROM table

Using PHP's mysql_query() function, we can execute the query and fetch the result rows using mysql_fetch_array():

$fetch = mysql_query("SELECT * FROM table");

while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
    $row_array['id'] = $row['id'];
    $row_array['col1'] = $row['col1'];
    $row_array['col2'] = $row['col2'];

    array_push($return_arr, $row_array);
}

This will populate the $return_arr array with associative arrays containing the database column values.

Building the JSON Array

To construct the JSON array in the desired format, we can loop through the $return_arr and create individual JSON objects:

$json_array = array();

foreach ($return_arr as $row) {
    $json_array[] = array(
        'id' => $row['id'],
        'title' => $row['col1'],
        'start' => "$year-$month-10",
        'url' => "http://yahoo.com/"
    );
}

In this example, we've hardcoded the start and url values for simplicity. You can modify these values to dynamically populate them from the database.

Encoding and Output

Finally, we can encode the $json_array into a JSON string using json_encode():

echo json_encode($json_array);

This will output a JSON string that can be used by the FullCalendar component to render the events dynamically.

以上是如何從 MySQL 資料庫建立 JSON 數組以在 FullCalendar 中動態顯示事件?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn