ksort() - 对数组按照键名排序 - php 数组函数
ksort()
(PHP 4, PHP 5, PHP 7)
对数组按照键名排序
说明
ksort(array &$array[,int $sort_flags= SORT_REGULAR]): bool对数组按照键名排序,保留键名到数据的关联。本函数主要用于关联数组。
参数
$array输入的数组。
$sort_flags可以用可选参数$sort_flags改变排序的行为,详情见sort()。
返回值
成功时返回TRUE
,或者在失败时返回FALSE
。
范例
Example #1ksort()例子
以上例程会输出:
a = orange b = banana c = apple d = lemon
参见
asort()
对数组进行排序并保持索引关系- 数组排序函数对比
A nice way to do sorting of a key on a multi-dimensional array without having to know what keys you have in the array first: Output from first var_dump: [0]=> array(3) { ["name"]=> string(3) "Bob" ["age"]=> int(8) ["colour"]=> string(3) "red" } [1]=> array(3) { ["name"]=> string(4) "Greg" ["age"]=> int(12) ["colour"]=> string(4) "blue" } [2]=> array(3) { ["name"]=> string(4) "Andy" ["age"]=> int(5) ["colour"]=> string(6) "purple" } } Output from 2nd var_dump: array(3) { [0]=> array(3) { ["name"]=> string(4) "Greg" ["age"]=> int(12) ["colour"]=> string(4) "blue" } [1]=> array(3) { ["name"]=> string(3) "Bob" ["age"]=> int(8) ["colour"]=> string(3) "red" } [2]=> array(3) { ["name"]=> string(4) "Andy" ["age"]=> int(5) ["colour"]=> string(6) "purple" } There's no checking on whether your array keys exist, or the array data you are searching on is actually there, but easy enough to add.
The function that justin at booleangate dot org provides works well, but be aware that it is not a drop-in replacement for ksort as is. While ksort sorts the array by reference and returns a status boolean, natksort returns the sorted array, leaving the original untouched. Thus, you must use this syntax: $array = natksort($array); If you want to use the more natural syntax: $status = natksort($array); Then use this modified version: function natksort(&$array) { $keys = array_keys($array); natcasesort($keys); foreach ($keys as $k) { $new_array[$k] = $array[$k]; } $array = $new_array; return true; }
I wrote this function to sort the keys of an array using an array of keynames, in order.
here 2 functions to ksort/uksort an array and all its member arrays function tksort(&$array) { ksort($array); foreach(array_keys($array) as $k) { if(gettype($array[$k])=="array") { tksort($array[$k]); } } } function utksort(&$array, $function) { uksort($array, $function); foreach(array_keys($array) as $k) { if(gettype($array[$k])=="array") { utksort($array[$k], $function); } } }
@thegrandoverseer you could also use the build-in php array functions to get exactly what you want to have:
Here is a function to sort an array by the key of his sub-array. Example This will be the output of the example: /*DESCENDING SORT*/ array(3) { ["peter"]=> array(2) { ["age"]=> int(21) ["gender"]=> string(4) "male" } ["mary"]=> array(2) { ["age"]=> int(20) ["gender"]=> string(6) "female" } ["john"]=> array(2) { ["age"]=> int(19) ["gender"]=> string(4) "male" } } /*ASCENDING SORT*/ array(3) { ["john"]=> array(2) { ["age"]=> int(19) ["gender"]=> string(4) "male" } ["mary"]=> array(2) { ["age"]=> int(20) ["gender"]=> string(6) "female" } ["peter"]=> array(2) { ["age"]=> int(21) ["gender"]=> string(4) "male" } }
ksort on an array with negative integers as keys yields some odd results. Not sure if this is a bad idea (negative key values) or what.
A real quick way to do a case-insensitive sort of an array keyed by strings: uksort($myArray, "strnatcasecmp");
Note that this function will output the given $fields in the order they were added to the data array and not automatically in numerical key order. To output in ascending key order, you'll need to ksort the array first (or use appropriate natural order sorting, depending on your keys). For example:
Here's a handy function for natural order sorting on keys. function natksort($array) { // Like ksort but uses natural sort instead $keys = array_keys($array); natsort($keys); foreach ($keys as $k) $new_array[$k] = $array[$k]; return $new_array; }
The first thing that I didn't find in description it's that this function return results from MIN value to MAX value, ex: [-5=>'', 0=>'', 5=>'' ] Also you should know that by default, it has correct sorting for keys that represented as string but has a number as value, ex: ['-5'=>'', '0'=>'', '5'=>'' ] Few examples with results: ----------------------------------------- DESCRIPTION: Keys are numbers + default flag (SORT_REGULAR) $arr = [ -5 => 'minus five', 0 => 'zero', 1 => 'one', 2 => 'two', 100 => 'hundred', ]; ksort($arr); print_r($arr); RESULT: Array ( [-5] => minus five [0] => zero [1] => one [2] => two [100] => hundred ) ----------------------------------------- DESCRIPTION: Keys are string numbers + default flag (SORT_REGULAR) $arr = [ '-5' => 'minus five', '0' => 'zero', '1' => 'one', '2' => 'two', '100' => 'hundred', ]; ksort($arr); print_r($arr); RESULT: Array ( [-5] => minus five [0] => zero [1] => one [2] => two [100] => hundred ) ----------------------------------------- DESCRIPTION: Keys are string numbers + SORT_STRING flag $arr = [ '-5' => 'minus five', '0' => 'zero', '1' => 'one', '2' => 'two', '100' => 'hundred', ]; ksort($arr, SORT_STRING); print_r($arr); RESULT: Array ( [-5] => minus five [0] => zero [1] => one [100] => hundred [2] => two ) ----------------------------------------- DESCRIPTION: Keys are string numbers + SORT_NUMERIC flag $arr = [ '-5' => 'minus five', '0' => 'zero', '1' => 'one', '2' => 'two', '100' => 'hundred', ]; ksort($arr, SORT_NUMERIC); print_r($arr); RESULT: Array ( [-5] => minus five [0] => zero [1] => one [2] => two [100] => hundred )
An example of reverse sorting a domain name by its name.
Note that ksort will NOT help you much if numeric and string keys are mixed together. produces (on PHP 5.3.6-4 with Suhosin-Patch) : array(4) { ["a"]=> string(1) "A" [0]=> string(1) "A" ["b"]=> string(1) "A" [1]=> string(1) "A" } array(4) { ["b"]=> string(1) "A" [0]=> string(1) "A" ["a"]=> string(1) "A" [1]=> string(1) "A" } note that the second array should be sorted by keys, but is even more messed up than the first one!
I wrote this function to sort meta_value in wordpress. I tried a lot of array sorting but neither of them work. But this is not suitable for multidimensional array. This is intended only for wordpress meta_value The problem is to sort below( the order should be ascending; alphabetically then numerically like A-Z then 0-9): 500-999 users 25-49 users All Sizes 1-4 users 5-9 users 10-24 users 250-499 users 1000-4999 5000-9999 The solution: function array_sort($arr){ if(is_array($arr)){ $numeric = array(); $string = array(); foreach($arr as $k => $v) { if(isset($v["meta_value"])){ $str = explode(" ",trim($v["meta_value"])); $firstWord = explode("-",trim($str[0])); }else{ $str = $v; $firstWord = explode("-",trim($str)); } $firstWord = $firstWord[0]; if(is_numeric($firstWord)) { $numeric[(int)$firstWord] = $v; }else{ $string[$firstWord] = $v; } unset($firstWord); } ksort($string,SORT_STRING); ksort($numeric,SORT_NUMERIC); return array_merge((array)$string, (array)$numeric); } return false; } The usage: $meta =get_post_meta($post_id,$meta_key); $sorted = array_sort($meta); The result: All Sizes 1-4 users 5-9 users 10-24 users 25-49 users 250-499 users 500-999 users 1000-4999 5000-9999
ksort and krsort fail to undestand scientific notation, https://bugs.php.net/bug.php?id=43053, therefore when sorting numeric keys, if the key is of the form 0.00001 php will represent it as 1.0E-5. These methods will assume this to be a string and therefore not organise your array as you may expect. When using value of this form for array keys use sprintf('%f', 0.00001) to generate the key, for smaller values the precision needs to be included e.g. sprintf('%0.10f', 0.00000001)
Be careful when using ksort for mixed type keys!! $a = array( 'first' => true, 0 => 'sally', ); $b = array( 0 => 'sally', 'first' => true, ); ksort($a); ksort($b); var_dump($a); var_dump($b); Output is: array( 0 => 'sally', 'first' => true, ) array( 'first' => true, 0 => 'sally', ) If you want same results for both arrays, use: ksort($a, SORT_STRING); The reason for that lays in the compare mechanism which would normally just typecast 'first' to an integer or 0 to a string when comparing it to each other. So you have to use SORT_STRING, otherwise you would lose information when 'first' is converted to int.
鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com
免责声明:我们致力于保护作者版权,注重分享,当前被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理!邮箱:344225443@qq.com)
图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!
内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)