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.
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!