Home >Database >Mysql Tutorial >How to Convert MySQL Database Data into a JSON Array?
Creating JSON Arrays from MySQL Databases
Building JSON arrays from MySQL database can be achieved in a straightforward manner. Here's a code sample that demonstrates how to retrieve data from a MySQL table and convert it into a JSON array:
$return_arr = 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); } echo json_encode($return_arr);
This code fetches all rows from the "table" table and constructs a JSON array in the following format:
[{"id":"1","col1":"col1_value","col2":"col2_value"},{"id":"2","col1":"col1_value","col2":"col2_value"}]
If you're working with dynamic event data for a fullcalendar, you can modify the code to generate a JSON array in the desired format, like this:
$year = date('Y'); $month = date('m'); $json_array = array(); //Fetch data from database and populate the JSON array foreach ($data from database as $row) { $json_array[] = array( 'id' => $row['id'], 'title' => $row['title'], 'start' => $year . '-' . $month . '-' . $row['start_date'], 'end' => $year . '-' . $month . '-' . $row['end_date'], 'url' => $row['url'] ); } echo json_encode($json_array);
This modified code assumes that your database has fields such as id, title, start_date, end_date, and url for each event. By fetching this data from the database, you can create a JSON array tailored specifically for your fullcalendar's needs.
The above is the detailed content of How to Convert MySQL Database Data into a JSON Array?. For more information, please follow other related articles on the PHP Chinese website!