Sort a 2D array by a column value
How can I sort this array by the value of the “order” key? Even though the values are currently sequential, they will not always be.
Array
(
[0] => Array
(
[hashtag] => a7e87329b5eab8578f4f1098a152d6f4
[title] => Flower
[order] => 3
)
[1] => Array
(
[hashtag] => b24ce0cd392a5b0b8dedc66c25213594
[title] => Free
[order] => 2
)
[2] => Array
(
[hashtag] => e7d31fc0602fb2ede144d18cdffd816b
[title] => Ready
[order] => 1
)
)
You can sort a 2D array by a specific column value using PHP’s array_multisort() function combined with array_column(). For your example array, the solution is:
array_multisort(array_column($yourArray, 'order'), SORT_ASC, $yourArray);
This will sort the array in ascending order based on the “order” key values.
Contents
- Basic Solution for Your Example
- Understanding the Solution
- Sorting in Different Orders
- Advanced Sorting Techniques
- Alternative Approaches
- Performance Considerations
- Complete Working Example
Basic Solution for Your Example
For your specific array, here’s the complete implementation:
<?php
// Your original array
$items = [
[
'hashtag' => 'a7e87329b5eab8578f4f1098a152d6f4',
'title' => 'Flower',
'order' => 3
],
[
'hashtag' => 'b24ce0cd392a5b0b8dedc66c25213594',
'title' => 'Free',
'order' => 2
],
[
'hashtag' => 'e7d31fc0602fb2ede144d18cdffd816b',
'title' => 'Ready',
'order' => 1
]
];
// Sort by the 'order' column in ascending order
array_multisort(array_column($items, 'order'), SORT_ASC, $items);
// Print the sorted array
print_r($items);
?>
The result will be:
Array
(
[0] => Array
(
[hashtag] => e7d31fc0602fb2ede144d18cdffd816b
[title] => Ready
[order] => 1
)
[1] => Array
(
[hashtag] => b24ce0cd392a5b0b8dedc66c25213594
[title] => Free
[order] => 2
)
[2] => Array
(
[hashtag] => a7e87329b5eab8578f4f1098a152d6f4
[title] => Flower
[order] => 3
)
)
Understanding the Solution
The array_multisort() function sorts multiple arrays or multidimensional arrays by columns. When combined with array_column(), it becomes a powerful tool for sorting 2D arrays.
How It Works:
-
array_column($items, 'order')extracts all values from the “order” key into a single array:[3, 2, 1] -
array_multisort()sorts this extracted array and then applies the same sorting order to the original multidimensional array -
SORT_ASCspecifies ascending order (you can also useSORT_DESCfor descending)
Sorting in Different Orders
Ascending Order (Default)
array_multisort(array_column($items, 'order'), SORT_ASC, $items);
Descending Order
array_multisort(array_column($items, 'order'), SORT_DESC, $items);
Numeric Sorting (for numeric values)
array_multisort(array_column($items, 'order'), SORT_NUMERIC, SORT_ASC, $items);
String Sorting (for alphabetical order)
array_multisort(array_column($items, 'title'), SORT_STRING, SORT_ASC, $items);
Advanced Sorting Techniques
Sorting by Multiple Columns
You can sort by multiple columns to handle ties:
// Sort by 'order' first, then by 'title' for items with same order
array_multisort(
array_column($items, 'order'), SORT_ASC,
array_column($items, 'title'), SORT_ASC,
$items
);
Custom Sorting Logic
For more complex sorting requirements:
// Sort by order, but with custom priority for certain values
$sort = [];
foreach ($items as $k => $v) {
$sort[$k] = $v['order'];
// Add custom logic here if needed
}
array_multisort($sort, SORT_ASC, $items);
Alternative Approaches
Using usort() with Custom Function
function sortByOrder($a, $b) {
return $a['order'] <=> $b['order'];
}
usort($items, 'sortByOrder');
Using array_uasort() for Associative Arrays
function sortByOrder($a, $b) {
return $a['order'] <=> $b['order'];
}
array_uasort($items, 'sortByOrder');
Using array_reduce() for Complex Sorting
$sorted = array_reduce($items, function($carry, $item) {
$carry[$item['order']][] = $item;
return $carry;
}, []);
// Then flatten the array in the desired order
$sorted = array_merge(...$sorted);
Performance Considerations
Performance Comparison
array_multisort() + array_column():
- Pros: Fastest for most cases, built-in functions, handles large arrays efficiently
- Cons: Less flexible for complex sorting logic
usort():
- Pros: More flexible, allows custom comparison logic
- Cons: Slower for very large arrays, can be more complex to write
When to Use Each Method
- Use
array_multisort()for simple, fast sorting by one or more columns - Use
usort()when you need custom comparison logic - Use
array_uasort()when you need to maintain key associations
Complete Working Example
Here’s a complete, practical example that handles various scenarios:
<?php
class ArraySorter {
/**
* Sort a 2D array by a specific column
*
* @param array $array The 2D array to sort
* @param string $column The column to sort by
* @param string $order 'ASC' or 'DESC'
* @param int $sortType SORT_REGULAR, SORT_NUMERIC, or SORT_STRING
* @return array The sorted array
*/
public static function sortByColumn($array, $column, $order = 'ASC', $sortType = SORT_REGULAR) {
if (empty($array) || !is_array($array)) {
return $array;
}
$columnValues = array_column($array, $column);
$sortOrder = ($order === 'DESC') ? SORT_DESC : SORT_ASC;
array_multisort($columnValues, $sortType, $sortOrder, $array);
return $array;
}
/**
* Sort by multiple columns with different orders
*
* @param array $array The 2D array to sort
* @param array $columns Array of ['column_name' => 'ASC/DESC']
* @param int $sortType SORT_REGULAR, SORT_NUMERIC, or SORT_STRING
* @return array The sorted array
*/
public static function sortByMultipleColumns($array, $columns, $sortType = SORT_REGULAR) {
if (empty($array) || !is_array($array) || empty($columns)) {
return $array;
}
$sortArgs = [];
foreach ($columns as $column => $order) {
$sortArgs[] = array_column($array, $column);
$sortArgs[] = ($order === 'DESC') ? SORT_DESC : SORT_ASC;
$sortArgs[] = $sortType;
}
$sortArgs[] = &$array;
call_user_func_array('array_multisort', $sortArgs);
return $array;
}
}
// Example usage:
$items = [
[
'hashtag' => 'a7e87329b5eab8578f4f1098a152d6f4',
'title' => 'Flower',
'order' => 3
],
[
'hashtag' => 'b24ce0cd392a5b0b8dedc66c25213594',
'title' => 'Free',
'order' => 2
],
[
'hashtag' => 'e7d31fc0602fb2ede144d18cdffd816b',
'title' => 'Ready',
'order' => 1
],
[
'hashtag' => 'f1234567890abcdef1234567890abcdef',
'title' => 'Apple',
'order' => 1
]
];
// Sort by 'order' column ascending
$sortedByOrder = ArraySorter::sortByColumn($items, 'order', 'ASC');
echo "Sorted by order (ASC):\n";
print_r($sortedByOrder);
// Sort by 'order' column descending
$sortedByOrderDesc = ArraySorter::sortByColumn($items, 'order', 'DESC');
echo "\nSorted by order (DESC):\n";
print_r($sortedByOrderDesc);
// Sort by multiple columns: first by 'order' ASC, then by 'title' ASC
$sortedMultiple = ArraySorter::sortByMultipleColumns($items, [
'order' => 'ASC',
'title' => 'ASC'
]);
echo "\nSorted by multiple columns:\n";
print_r($sortedMultiple);
?>
This complete solution provides a robust way to sort 2D arrays by column values, with error handling and support for various sorting scenarios.
Sources
- PHP: array_multisort - Manual - Official PHP documentation explaining the array_multisort function
- php - Sort a 2d array by a column value - Stack Overflow - Community discussion with practical examples and one-line solutions
- How to Sort Multi-dimensional Array by Key Value in PHP - CodexWorld - Tutorial showing array_column and array_multisort combination
- How to Sort Multi-Dimensional Array by Key Value in PHP? - GeeksforGeeks - Comprehensive guide with examples
- php - Sort multi-dimensional array by specific key - Stack Overflow - Additional approach examples and best practices
- PHP array_multisort() Function - W3Schools - Beginner-friendly explanation with examples
- How to sort a multi-dimension array by value in PHP - Virendra’s TechTalk - Alternative approach using usort function
Conclusion
Sorting a 2D array by a specific column value in PHP is straightforward using the array_multisort() function combined with array_column(). Here are the key takeaways:
- The most efficient method is
array_multisort(array_column($array, 'column'), SORT_ASC, $array) - For simple sorting needs, this one-liner approach is fast and easy to implement
- For complex sorting requirements, consider using
usort()with custom comparison functions - Multiple column sorting is possible by chaining additional parameters in
array_multisort() - Error handling should be implemented when working with dynamic data to prevent issues with missing keys
The solution provided works reliably with your example array and can handle various data types and sorting requirements. For production code, consider encapsulating the logic in a reusable function or class as demonstrated in the complete example.