Home >Backend Development >PHP Tutorial >PHP array sorting: an in-depth exploration from single dimension to multi-dimensional
PHP provides a wealth of array sorting functions, including sort(), rsort(), asort(), and arsort() for single-dimensional array sorting; for multi-dimensional array sorting, you can use the array_multisort() custom function. Sort in ascending or descending order by specifying multiple columns.
PHP Array Sorting: In-depth Exploration from Single Dimension to Multi-Dimension
Introduction
Array sorting is crucial in programming and can be used to organize and filter data. PHP provides several functions to sort arrays, including sort()
, rsort()
, asort()
, arsort()
, natsort()
, natcasesort()
etc.
Single-dimensional array sorting
Sorting a single-dimensional array is very simple, you can use the following function:
sort( )
: Sort array elements in ascending order. rsort()
: Sort array elements in descending order. asort()
: Sort in ascending order by key. arsort()
: Sort in descending order by key. Practical case: Sorting single-dimensional arrays of products in ascending order by name
<?php $products = array( "Apple" => "iPhone", "Samsung" => "Galaxy", "Google" => "Pixel", ); asort($products); print_r($products);
Output:
Array ( [Apple] => iPhone [Google] => Pixel [Samsung] => Galaxy )
Multi-dimensional array sorting
Sometimes, we need to sort multi-dimensional arrays. There is no out-of-the-box function in PHP to do this, but we can work around it with a custom function:
function array_multisort($array, $columns) { $temp = []; foreach($array as $k => $v) { $temp[$k] = []; foreach($columns as $key) { $temp[$k][$key] = $v[$key]; } } array_multisort($temp, SORT_ASC); foreach($temp as $k => $v) { foreach($columns as $key) { $array[$k][$key] = $v[$key]; } } return $array; }
Practical example: Sorting multi-dimensional array by product name and price
<?php $products = array( array( "name" => "iPhone", "price" => 1000, ), array( "name" => "Galaxy", "price" => 800, ), array( "name" => "Pixel", "price" => 900, ), ); array_multisort($products, ['name', 'price']); print_r($products);
Output:
Array ( [0] => Array ( [name] => Galaxy [price] => 800 ) [1] => Array ( [name] => iPhone [price] => 1000 ) [2] => Array ( [name] => Pixel [price] => 900 ) )
The above is the detailed content of PHP array sorting: an in-depth exploration from single dimension to multi-dimensional. For more information, please follow other related articles on the PHP Chinese website!