Skip to content
PHP Logo

How can PHP be used to dynamically populate an array with data from a MySQL database to achieve alphabetical sorting and grouping?

To achieve alphabetical sorting and grouping of data from a MySQL database in PHP, you can query the database to retrieve the data, store it in an array, and then use PHP functions to sort and group the data alphabetically.

php
// Connect to the database
$connection = mysqli_connect("localhost", "username", "password", "database");

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

// Initialize an empty array to store the data
$data = array();

// Loop through the results and populate the array
while ($row = mysqli_fetch_assoc($result)) {
    $first_letter = strtoupper(substr($row['name'], 0, 1));
    $data[$first_letter][] = $row;
}

// Sort the array alphabetically
ksort($data);

// Display the sorted and grouped data
foreach ($data as $letter => $group) {
    echo "<h2>$letter</h2>";
    foreach ($group as $item) {
        echo $item['name'] . "<br>";
    }
}