![]() Use array_multisort to get there: array_multisort($array1, $array2) Īs of PHP 5.5.0 you can use array_column to extract a column from a multi dimensional array and sort the array on that column: array_multisort(array_column($array, 'foo'), SORT_DESC, $array) The expected result here would be: $array2 = array('c', 'a', 'b') // the sorted order of $array1 Return $b - $a // descendingĪnd then there's the peculiar array_multisort, which lets you sort one array based on another: $array1 = array( 4, 6, 1) Again, just think in terms of teaching PHP how to tell which of two items is "greater" let PHP do the actual sorting.Īlso for all of the above, to switch between ascending and descending order simply swap the $a and $b arguments around. That's how simple sorting a complex multi-dimensional array can be. That's all that's needed: function cmp(array $a, array $b) ) That function takes two elements and must return 0 if these elements are considered equal, a value lower than 0 if the first value is lower and a value higher than 0 if the first value is higher. To do that, you need to create a comparison function. PHP does not simply "know" what to do with a complex value like array('foo' => 'bar', 'baz' => 42) though so you need to tell it. The above sort and related functions work on simple values that they know how to compare and sort. If you want to sort $array by the key 'foo' of each entry, you need a custom comparison function. Multi dimensional arrays, including arrays of objects $array = array( See for an overview and links to further details. ![]() The difference between those is merely whether key-value associations are kept (the " a" functions), whether it sorts low-to-high or reverse (" r"), whether it sorts values or keys (" k") and how it compares values (" nat" vs. Basic one dimensional arrays $array = array(3, 5, 2, 8)
0 Comments
Leave a Reply. |
Details
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |