$hierarchy $hierarchy) accesses the related value (priority value) from the $hierarchy (lookup) array for both $a and $b.The => operator not only returns the value on its right, it also affords access to variables declared outside of the custom function's scope (previously use($hierarchy) would have been required). It is common practice to use generic variable names for this reason. It will be unknown what these strings will be or in what order the arguments will be delivered. The $a and the $b parameters are two items (key strings in this case). fn($a, $b) => is array function syntax which became available since PHP7.4.uksort() is a native sorting function that makes comparisons on the keys of the input array and the comparison logic is encapsulated in a custom function ( user function).Uksort($array, fn($a, $b) => $hierarchy $hierarchy) This would be the best use of a native PHP sorting function.Ĭode: ( Demo) function sort_custom(&$array) You only need to establish a lookup array with your possible values then leverage that array inside of a uksort() call. Even declaring letters to denote priority is unnecessarily tedious. Much of your code does not need to exist. finally copy the sorted temp array to the original array assign the values from the original array to the temp array fill temp array with the key-value pair from the matching input array set the known hierarchy ordered alphabetically by the keys The way I did it seem too complicated for what it's supposed to do, so maybe there is a better/more efficient way: public function sort_custom(&$array) I want to sort it in the correct order, so for the example input array above, the result should be: $array = [ I am then given an input key-value array which can consist of any of the units, but not necessarily all of them, and not always in the correct order: $array = [ I have a known hierarchy of the organization units, by descending order: $hierarchy = [
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |