Custom sort associative array – PHP

Suppose you have an associative array in PHP with key-value pair. If you loop through it, all the values will be displayed in the order they are added to the array. To learn how to customize the sorting of an associative array, keep reading this.

We will use a database called “classicmodels”, which can be found in the source files attached below. First, we will connect with the database and get all the columns of the desired table.


    $conn = mysqli_connect("localhost:8889", "root", "root", "classicmodels");
    $result = mysqli_query($conn, "SELECT * FROM customers");

    $columns = [];
    while ($row = mysqli_fetch_object($result))
        foreach ($row as $col_name => $col_value)
            array_push($columns, $col_name);
    mysqli_data_seek($result, 0);

If you do print_r($columns); after this, then you will see all the column names of that table. Now create an array that holds the desired sorting of columns.

$columns_order = [
    "customerNumber" => "ID",
    "customerName" => "Name",
    "salesRepEmployeeNumber" => "Sales rep Employee ID",
    "contactFirstName" => "Contact peron name",
    "phone" => "Mobile",
    "addressLine1" => "Address line 1",
    "addressLine2" => "Address line 2",
    "city" => "City",
    "state" => "State",
    "postalCode" => "Zip code",
    "country" => "Country",
    "creditLimit" => "Credit limit"

The key of each element is the name of the column in the database, and the value is the text that will be shown against that column. Now comes the most important part, to display the first table row which is usually the heading, do a foreach loop on this array and display the value in TH:

        <?php foreach ($columns_order as $key => $value): ?>
                <?php echo $value; ?>
        <?php endforeach; ?>

To display the data as in new order, loop through each record in the database, then run a nested foreach loop like above, and show the values based on key of an associative array:

<?php while ($row = mysqli_fetch_object($result)): ?>
        <?php foreach ($columns_order as $key => $value): ?>
                <?php echo $row->{$key}; ?>
        <?php endforeach; ?>
<?php endwhile; ?>

Try changing the order of columns from $columns_order array. You can also try deleting columns from this array, so if you want to remove some columns from the table tag, you can simply remove that from $columns_order array.

Leave a Reply

Please disable your adblocker or whitelist this site!