How to Efficiently Sort a Multidimensional PHP Array by a Nested Field?
In PHP, it is possible to encounter multidimensional arrays representing tabular data, where each element holds an associative array of field-value pairs. The task of sorting this data by a specific field within the nested arrays can be achieved with ease.
Consider the following database-alike array:
$data = [ [ 'name' => 'Sony TV', 'price' => 600.00 ], [ 'name' => 'LG TV', 'price' => 350.00 ], [ 'name' => 'Samsung TV', 'price' => 425.00 ] ];
To sort this array by the 'price' field, one can employ the array_multisort() function along with the array_column() function, which extracts a specific column (field) from the multidimensional array. The following snippet accomplishes this:
array_multisort(array_column($data, 'price'), SORT_ASC, $data);
This call will rearrange the array in ascending order based on the 'price' field while discarding the original outer array keys. The resulting sorted array will appear as:
[ [ 'name' => 'LG TV', 'price' => 350.00 ], [ 'name' => 'Samsung TV', 'price' => 425.00 ], [ 'name' => 'Sony TV', 'price' => 600.00 ] ]
Alternatively, for PHP versions before 8, a two-liner solution was required due to reference passing restrictions:
$col = array_column($data, 'price'); array_multisort($col, SORT_ASC, $data);
The above is the detailed content of How to Sort a Multidimensional PHP Array by a Nested Field Efficiently?. For more information, please follow other related articles on the PHP Chinese website!