What is the best way to aggregate data in PHP when querying a MySQL database to avoid duplication in JSON output?

When querying a MySQL database in PHP to retrieve data that may contain duplicates, the best way to aggregate the data and avoid duplication in the JSON output is to use an associative array to store unique values based on a specific key. This way, you can ensure that only unique values are included in the final JSON output.

// Query the database to retrieve data
$query = "SELECT * FROM table";
$result = mysqli_query($connection, $query);

// Initialize an empty associative array to store unique values
$data = array();

// Loop through the query results and aggregate data
while ($row = mysqli_fetch_assoc($result)) {
    // Use a specific key to check for duplicates
    $key = $row['key'];

    // Check if the key already exists in the data array
    if (!array_key_exists($key, $data)) {
        // Add the row to the data array if the key is unique
        $data[$key] = $row;
    }
}

// Convert the aggregated data to JSON format
$json_output = json_encode(array_values($data));

// Output the JSON data
echo $json_output;