Sorting multidimensional arrays is a common task when working with data in PHP. In this tutorial, we will explore how to sort a 2D array by a specific column value.
Introduction to Multidimensional Arrays
A multidimensional array is an array that contains other arrays as its elements. Each inner array represents a row of data, and the keys of these inner arrays represent columns. For example:
$array = [
[
'hashtag' => 'a7e87329b5eab8578f4f1098a152d6f4',
'title' => 'Flower',
'order' => 3,
],
[
'hashtag' => 'b24ce0cd392a5b0b8dedc66c25213594',
'title' => 'Free',
'order' => 2,
],
[
'hashtag' => 'e7d31fc0602fb2ede144d18cdffd816b',
'title' => 'Ready',
'order' => 1,
],
];
Sorting Using usort()
The usort()
function is used to sort an array by a user-defined comparison function. To sort our multidimensional array by the order
column, we can use the following code:
function compareOrder($a, $b) {
return $a['order'] - $b['order'];
}
usort($array, 'compareOrder');
In PHP 7 and later, you can use an anonymous function with the spaceship operator (<=>
) to simplify the comparison:
usort($array, function($a, $b) {
return $a['order'] <=> $b['order'];
});
Alternatively, in PHP 7.4 and later, you can use an arrow function:
usort($array, fn($a, $b) => $a['order'] <=> $b['order']);
Sorting Using array_multisort()
Another way to sort a multidimensional array is by using the array_multisort()
function. This function sorts multiple arrays and maintains their index associations.
To use array_multisort()
, we first need to extract the column values into a separate array:
$keys = array_column($array, 'order');
array_multisort($keys, SORT_ASC, $array);
This will sort our multidimensional array by the order
column in ascending order.
Preserving Key Associations
If you need to preserve key associations after sorting, you can use the uasort()
function instead of usort()
. The syntax for uasort()
is similar to usort()
:
function compareOrder($a, $b) {
return $a['order'] - $b['order'];
}
uasort($array, 'compareOrder');
Sorting by Multiple Columns
To sort a multidimensional array by multiple columns, you can modify the comparison function to check for multiple conditions. Here’s an example:
usort($array, function($a, $b) {
$retval = $a['order'] <=> $b['order'];
if ($retval == 0) {
$retval = $a['suborder'] <=> $b['suborder'];
if ($retval == 0) {
$retval = $a['details']['subsuborder'] <=> $b['details']['subsuborder'];
}
}
return $retval;
});
This will sort our multidimensional array by the order
, then suborder
, and finally subsuborder
columns.
Conclusion
Sorting multidimensional arrays is a common task in PHP. By using the usort()
or array_multisort()
functions, you can easily sort your data by specific column values. Remember to preserve key associations if needed and use comparison functions for more complex sorting scenarios.