This includes multidimensional arrays, including arrays of objects, and sorting one array based on another.
Sorting Functions:
PHP requires a custom comparison function to sort complex values.
Steps:
Create a comparison function that takes two elements and returns:
Use one of these functions:
If sorting by a numeric key:
function cmp(array $a, array $b) { return $a['baz'] - $b['baz']; }
If sorting an array of objects:
function cmp($a, $b) { return $a->baz - $b->baz; }
For primary sorting by one field (e.g., "foo") and secondary sorting by another (e.g., "baz"):
function cmp(array $a, array $b) { if (($cmp = strcmp($a['foo'], $b['foo'])) !== 0) { return $cmp; } else { return $a['baz'] - $b['baz']; } }
To sort into a specific order (e.g., "foo", "bar", "baz"):
function cmp(array $a, array $b) { static $order = array('foo', 'bar', 'baz'); return array_search($a['foo'], $order) - array_search($b['foo'], $order); }
To sort one array based on another:
array_multisort($array1, $array2);
As of PHP 5.5.0, you can use array_column to extract a specific column and sort the array accordingly:
array_multisort(array_column($array, 'foo'), SORT_DESC, $array);
The above is the detailed content of How to Sort Arrays and Data in PHP?. For more information, please follow other related articles on the PHP Chinese website!