Home >Database >Mysql Tutorial >How to Convert MySQL Database Data into a JSON Array?

How to Convert MySQL Database Data into a JSON Array?

Linda Hamilton
Linda HamiltonOriginal
2024-11-24 18:47:26242browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn