|
krsort
Sort an array by key in reverse order
(PHP 4, PHP 5)
Example 310. krsort() example<?php The above example will output: d = lemon Code Examples / Notes » krsort08-aug-2005 02:37
To create a natural reverse sorting by keys, use the following function: <?php function natkrsort($array) { $keys = array_keys($array); natsort($keys); foreach ($keys as $k) { $new_array[$k] = $array[$k]; } $new_array = array_reverse($new_array, true); return $new_array; } ?> lolo
If you want to emulate the krsort function for an older version of php, you can use this piece of code: function KeyComp($a, $b) { return -(strcmp($a,$b)); } function krsort($MyArray) { uksort($MyArray, "KeyComp"); } Maybe obvious and useless, but who knows... peter
Best deal sorting: This is a function that will sort an array with integer keys (weight) and float values (cost) and delete 'bad deals' - entries that are more costly than other entries that have greater or equal weight. Input: an array of unsorted weight/cost pairs Output: none function BEST_DEALS($myarray) { // most weight for least cost: // © Peter Kionga-Kamau, http://www.pmkmedia.com // thanks to Nafeh for the reversal trick // free for unrestricted use. krsort($myarray, SORT_NUMERIC); while(list($weight, $cost) = each($myarray)) { // delete bad deals, retain best deals: if(!$lastweight) { $lastweight=$weight; $lastcost = $cost; } else if($cost >= $lastcost) unset($myarray[$weight]); else { $lastweight=$weight; $lastcost = $cost; } } ksort($myarray); } |
Change Languagearray_change_key_case array_chunk array_combine array_count_values array_diff_assoc array_diff_key array_diff_uassoc array_diff_ukey array_diff array_fill_keys array_fill array_filter array_flip array_intersect_assoc array_intersect_key array_intersect_uassoc array_intersect_ukey array_intersect array_key_exists array_keys array_map array_merge_recursive array_merge array_multisort array_pad array_pop array_product array_push array_rand array_reduce array_reverse array_search array_shift array_slice array_splice array_sum array_udiff_assoc array_udiff_uassoc array_udiff array_uintersect_assoc array_uintersect_uassoc array_uintersect array_unique array_unshift array_values array_walk_recursive array_walk array arsort asort compact count current each end extract in_array key krsort ksort list natcasesort natsort next pos prev range reset rsort shuffle sizeof sort uasort uksort usort |