PASSWORD RESET

Your destination for complete Tech news

How to sort a multi dimensional array in PHP?

305 0
< 1 min read

To sort a multi-dimensional array in PHP, you can use the usort() function. This function allows you to define a custom comparison function that determines the order of the elements in the array.

Here is an example of how you can use the usort() function to sort a multi-dimensional array:

<?php

$items = [
    ['id' => 1, 'name' => 'Item 1'],
    ['id' => 2, 'name' => 'Item 2'],
    ['id' => 3, 'name' => 'Item 3'],
];

// Define the comparison function
function compare($a, $b) {
    if ($a['id'] == $b['id']) {
        return 0;
    }
    return ($a['id'] < $b['id']) ? -1 : 1;
}

// Sort the array using the comparison function
usort($items, 'compare');

print_r($items);

The output of the above code will be:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Item 1
        )

    [1] => Array
        (
            [id] => 2
            [name] => Item 2
        )

    [2] => Array
        (
            [id] => 3
            [name] => Item 3
        )
)

Alternatively, you can use the array_multisort() function to sort a multi-dimensional array by one or more dimensions. This function allows you to specify the sort order and the sort type (e.g. ascending or descending) for each dimension.

Here is an example of how you can use the array_multisort() function to sort a multi-dimensional array:

<?php

$items = [
    ['id' => 3, 'name' => 'Item 3'],
    ['id' => 1, 'name' => 'Item 1'],
    ['id' => 2, 'name' => 'Item 2'],
];

// Sort the array by the 'id' dimension in ascending order
array_multisort(array_column($items, 'id'), SORT_ASC, $items);

print_r($items);

The output of the above code will be the same as the previous example.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.