How to Sort Multi-Dimensional Array by Key Value in PHP?
Last Updated :
29 Jul, 2024
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";
}
?>
OutputName: 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";
}
?>
OutputID: 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);
?>
OutputArray
(
[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);
?>
OutputArray
(
[0] => Array
(
[id] => 2
[name] => John
[age] => 28
)
[1] => Array
(
[id] => 1
[name] => Jane
...
Similar Reads
How to Sort a Multi-dimensional Array by Value
What is Sorting?Arranging data in an increasing or decreasing fashion according to their values is called Sorting. Below are shown some processes for sorting arrays of several dimensions. Sorting a 1-Dimensional array:We can sort any Dimensional array using the sort method in C++. Syntax: sort(arr,
11 min read
How to get specific key value from array in PHP ?
In this article, we will see how to get specific key values from the given array. PHP array is a collection of items that are stored under keys. There are two possible types of keys: strings and integers. For any type of key, there is a common syntax to get a specific value by key â square brackets.
3 min read
How to display array structure and values in PHP ?
In this article, we will discuss how to display the array structure and values in PHP. To display the array structure and its values, we can use var_dump() and print_r() functions. It includes Array sizeArray valuesArray value with IndexEach value data type We will display the array structure using
2 min read
How to create an array with key value pairs in PHP?
In PHP, an array with key-value pairs is called an associative array. It maps specific keys to values, allowing you to access elements using custom keys rather than numerical indices. Keys are strings or integers, while values can be of any data type.Here we have some common approaches to create an
2 min read
How to Sort JSON Array in JavaScript by Value ?
Sorting is the process of arranging elements in a specific order. In JavaScript, you can sort a JSON array by value using various methods as listed and discussed below with their practical implementation. Table of Content Using sort() FunctionUsing Array.prototype.reduce()Using Bubble SortUsing sort
3 min read
How to check foreach Loop Key Value in PHP ?
In PHP, the foreach loop can be used to loop over an array of elements. It can be used in many ways such asTable of ContentUsing the for-each loop with simple valuesUsing the foreach loop with Key-Value pairsUsing array_keys Function to Access Keys and ValuesUsing array_walk Function for IterationUs
3 min read
How to use array_merge() and array_combine() in PHP ?
In this article, we will discuss about how to use array_merge() and array_combine() functions in PHP. Both functions are array based functions used to combine two or more arrays using PHP. We will see each function with syntax and implementation array_merge() FunctionThis function merges the two or
3 min read
How to get total number of elements used in array in PHP ?
In this article, we will discuss how to get total number of elements in PHP from an array. We can get total number of elements in an array by using count() and sizeof() functions. Using count() Function: The count() function is used to get the total number of elements in an array. Syntax: count(arra
2 min read
How to Check an Array is Sorted or Not in PHP?
Given an array, the task is to check whether the given array is sorted or not. Arrays are often used to store and manipulate data. One common task is to check if an array is sorted in ascending or descending order. This article will explore different approaches to determine whether an array is sorte
3 min read
How to Sort a Multidimensional Array in JavaScript by Date ?
Sorting a Multidimensional Array by date consists of ordering the inner arrays based on the date values. This needs to be done by converting the date representation into the proper comparable formats and then applying the sorting function to sort the array in ascending or descending order. Below are
2 min read