Sorting Multidimensional Arrays by Inner Array Field in PHP [duplicate]
Consider a multidimensional array representing a database-like structure, where each element denotes a row with inner arrays containing field name-value pairs. For instance:
Array ( [0] => Array ( [name] => 'Sony TV' [price] => 600.00 ) [1] => Array ( [name] => 'LG TV' [price] => 350.00 ) [2] => Array ( [name] => 'Samsung TV' [price] => 425.00 ) }
The goal is to sort these rows based on the "price" field. The desired result is:
Array ( [0] => Array ( [name] => 'LG TV' [price] => 350.00 ) [1] => Array ( [name] => 'Samsung TV' [price] => 425.00 ) [2] => Array ( [name] => 'Sony TV' [price] => 600.00 ) }
Solution:
To achieve this sorting, PHP offers the following simple solution:
array_multisort(array_column($yourArray, "price"), SORT_ASC, $yourArray);
Alternatively, the following snippet can be used to preserve outer array keys:
$col = array_column($yourArray, "price"); array_multisort($col, SORT_ASC, SORT_NUMERIC, $yourArray);
The above is the detailed content of How to Sort a Multidimensional Array in PHP by an Inner Array\'s Field?. For more information, please follow other related articles on the PHP Chinese website!