Open In App

How to Sort Multi-Dimensional Array by Key Value in PHP?

Last Updated : 29 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Sorting a multi-dimensional array by key value in PHP can be useful in various scenarios, such as organizing data for display or processing. In this article, we will explore different approaches to achieve this.

Approach 1: Sort Multi-Dimensional Array using array_multisort() Function

This approach uses the array_multisort() function to sort a multi-dimensional array by a specified key.

Syntax:

array_multisort(array_column($array, 'key_to_sort_by'), SORT_ASC, $array);

Example: This example uses array_multisort() function to sort the Multi-dimensional Array by Key Value in PHP.

PHP
<?php
  
$array = [
    ['name' => 'Prasad', 'age' => 25],
    ['name' => 'Saurabh', 'age' => 30],
    ['name' => 'Manohar', 'age' => 20]
];

array_multisort(array_column($array, 'age'), SORT_ASC, $array);

foreach ($array as $item) {
    echo "Name: " . $item['name'] . ", Age: " . $item['age'] . "\n";
}

?>

Output
Name: Manohar, Age: 20
Name: Prasad, Age: 25
Name: Saurabh, Age: 30

Approach 2: Sort Multi-Dimensional Array using a Custom Sorting Function with usort() Function

This approach uses a custom sorting function with the usort() function to sort a multi-dimensional array by a specified key.

Syntax:

usort($array, function($a, $b) {
return $a['key_to_sort_by'] <=> $b['key_to_sort_by'];
});

Example: This example uses custom sorting function with usort() to sort the Multi-dimensional Array by Key Value in PHP.

PHP
<?php
  
$array = [
    ['id' => 2, 'name' => 'Prasad'],
    ['id' => 1, 'name' => 'Saurabh'],
    ['id' => 3, 'name' => 'Manohar']
];

usort($array, function($a, $b) {
    return $a['id'] <=> $b['id'];
});

foreach ($array as $item) {
    echo "ID: " . $item['id'] . ", Name: " . $item['name'] . "\n";
}

?>

Output
ID: 1, Name: Saurabh
ID: 2, Name: Prasad
ID: 3, Name: Manohar

using the uasort() Function with a Custom Comparison Function

This approach utilizes the uasort() function, which is similar to usort() but preserves the keys of the array, making it suitable when the keys themselves carry significance. A custom comparison function is provided to uasort() to dictate the sorting logic based on a specific key within the sub-arrays.

Syntax:

uasort($array, function($a, $b) {
return $a['key_to_sort_by'] <=> $b['key_to_sort_by'];
});

Example: In this example, we use uasort() to sort a multi-dimensional array by a key value, while maintaining the association between keys and elements. This is particularly useful when the keys are meaningful, such as identifiers or non-numeric indexing.

PHP
<?php
$people = [
    ['id' => 2, 'name' => 'John', 'age' => 28],
    ['id' => 1, 'name' => 'Jane', 'age' => 22],
    ['id' => 3, 'name' => 'Doe', 'age' => 54]
];

// Custom comparison function
function compareByAge($a, $b) {
    return $a['age'] <=> $b['age'];
}

// Sort each sub-array using array_walk() and a custom sort function
array_walk($people, function(&$value) use ($people) {
    usort($people, 'compareByAge');
});

// Print the sorted array
print_r($people);
?>

Output
Array
(
    [1] => Array
        (
            [id] => 1
            [name] => Jane
            [age] => 22
        )

    [0] => Array
        (
            [id] => 2
            [name] => John
     ...

Using array_walk() and a Custom Sort Logic

Using `array_walk()` and a custom sort logic involves iterating through the array and applying a user-defined sorting function to each element. This method ensures that each sub-array is sorted based on a specified key, providing a flexible approach for sorting multi-dimensional arrays.

Example

PHP
<?php
$people = [
    ['id' => 2, 'name' => 'John', 'age' => 28],
    ['id' => 1, 'name' => 'Jane', 'age' => 22],
    ['id' => 3, 'name' => 'Doe', 'age' => 54]
];

// Custom comparison function
function compareByAge($a, $b) {
    return $a['age'] <=> $b['age'];
}

// Sort each sub-array using array_walk() and a custom sort function
array_walk($people, function(&$value) use ($people) {
    usort($people, 'compareByAge');
});

// Print the sorted array
print_r($people);
?>

Output
Array
(
    [0] => Array
        (
            [id] => 2
            [name] => John
            [age] => 28
        )

    [1] => Array
        (
            [id] => 1
            [name] => Jane
     ...

Next Article

Similar Reads