uasort() - 使用用户自定义的比较函数对数组中的值进行排序并保持索引关联 - php 数组函数
uasort()
(PHP 4, PHP 5, PHP 7)
使用用户自定义的比较函数对数组中的值进行排序并保持索引关联
说明
uasort(array &$array,callable$value_compare_func): bool本函数对数组排序并保持索引和单元之间的关联。
主要用于对那些单元顺序很重要的结合数组进行排序。比较函数是用户自定义的。
Note:If two members compare as equal, their relative order in the sorted array is undefined.
参数
$array输入的数组。
$value_compare_func用户自定义比较函数的例子请参考usort()和uksort()。
返回值
成功时返回TRUE
,或者在失败时返回FALSE
。
范例
Example #1uasort()的基本例子
以上例程会输出:
Array ( [a] => 4 [b] => 8 [c] => -1 [d] => -9 [e] => 2 [f] => 5 [g] => 3 [h] => -4 ) Array ( [d] => -9 [h] => -4 [c] => -1 [e] => 2 [g] => 3 [a] => 4 [f] => 5 [b] => 8 )
参见
usort()
使用用户自定义的比较函数对数组中的值进行排序- 数组排序函数对比
a quick reminder on the syntax if you want to use uasort in a Class or Object:
If you want to keep the order when two members compare as equal, use this. returns Array ( [e] => Array ( [l] => E [n] => 2 ) [b] => Array ( [l] => B [n] => 2 ) [d] => Array ( [l] => D [n] => 2 ) [c] => Array ( [l] => C [n] => 1 ) [a] => Array ( [l] => A [n] => 1 ) ) Array ( [b] => Array ( [l] => B [n] => 2 ) [d] => Array ( [l] => D [n] => 2 ) [e] => Array ( [l] => E [n] => 2 ) [a] => Array ( [l] => A [n] => 1 ) [c] => Array ( [l] => C [n] => 1 ) ) https://bugs.php.net/bug.php?id=53341
An Example using anonymous function. Anonymous functions make some time the code easier to understand. returns Array ( [3] => Orange6 [0] => Orange9 [2] => Orange10 [1] => Orange11 [4] => Orange15 )
User "php at clement dot hk" already provided a stable uasort function, but I find this wrapper much shorter and easier to understand: https://github.com/vanderlee/PHP-stable-sort-functions/blob/master/classes/StableSort.php function stable_uasort(array &$array, $value_compare_func) { $index = 0; foreach ($array as &$item) { $item = array($index++, $item); } $result = uasort($array, function($a, $b) use($value_compare_func) { $result = call_user_func($value_compare_func, $a[1], $b[1]); return $result == 0 ? $a[0] - $b[0] : $result; }); foreach ($array as &$item) { $item = $item[1]; } return $result; }
Difference between uasort() and usort(), the missing example ... *** uasort($arr, 'so') output: *** usort($arr, 'so') output:
//this fix the problem of if any of these sort functions evaluates two members as equal then the order is undefined (the sorting is not stable). $pos=0; foreach($values as $k => $v) $tosort[$k]=array($v,$pos++); uasort($tosort,function($a, $b) { if($a[0] != $b[0])return ($a[0] $v) $values[$k]=$v[0];
I tried using some of the previous built multisorts, but they weren't working as expected. So, I made my own Class, and it seems to work wonderfully. Here is the code:
To shuffle assoc array preserving keys just do this:
Use example: $array[0]['Fator1']=7; $array[0]['Fator2']="Name"; $array[1]['Fator1']=5; $array[1]['Fator2']="Name"; $array[2]['Fator1']=7; $array[2]['Fator2']="NameDiferente"; ..... We want to order by Fator1, then Fator2, then: function Compare($ar1, $ar2) { if ($ar1['Fator1']$ar2['Fator1']) return 1; if ($ar1['Fator2']$ar2['Fator2']) return 1; return 0; } To sort now, we use: uasort($array, 'Compare');
Is it just me, or are the examples below misleading, and actually demonstrating situations that would be more appropriate for usort()? After trying to make sense of the uasort() description, it sounds like it's more for sorting a 1D array like this: "john" => "$23.12" "tim" => "$6.50" "bob" => "$18.54" and getting back: "tim" => "$6.50" "bob" => "$18.54" "john" => $23.12" (assuming, of course, that your sort function is lopping off the $ and evaluating as a number -- which would complicate the use of asort() ;)
Keep in mind that PHP sorting functions are not reliable to handle "stable sorting", even since PHP7+. It might work on small arrays, but not on "big" ones (100 items are enough for the stable sorting to fail). To ensure $b === $a, use a 3rd-party stable sorting function: http://php.net/manual/en/function.uasort.php#121283
My simple and effective solution for sort multi-dimensional array by any key:
Just expanding on php arobase kochira period com's method: If you are looking to sort a multi-D array by a specific column and have entries in both upper and lower case, simply drop the entries to lowercase before doing the strcmp.
Here is a little sort function that actually uses a dynamic callback for usort to do it's thing. It assumes your data is in the form of: $data = array( array('ID'=>'6','LAST'=>'Holmes','FIRST'=>'Dan'), array('ID'=>'1234','LAST'=>'Smith','FIRST'=>'Agent K'), array('ID'=>'2','LAST'=>'Smith','FIRST'=>'Agent J'), array('ID'=>'4','LAST'=>'Barney','FIRST'=>'Bob')); Now, you want to sort on one or more cols, don't you? masort($data, 'LAST,FIRST'); or masort($data,array('FIRST','ID')); Of course you could add a bunch to it (like numeric comparison if appropriate, desc/asc, etc) but it works for me. function masort(&$data, $sortby){ if(is_array($sortby)){ $sortby = join(',',$sortby); } uasort($data,create_function('$a,$b','$skeys = split(\',\',\''.$sortby.'\'); foreach($skeys as $key){ if( ($c = strcasecmp($a[$key],$b[$key])) != 0 ){ return($c); } } return($c); ')); } Notice that I am splitting the string in the comparison function? While this is certainly slower, it was the only way I would find to "pass" and "array". If anyone has a better way, please suggest. Then inside, we (string) compare the values only moving to the next key if the values are the same...and so on, and so on.
// Anonumous functions uasort($collection, array($this, function($a, $b){ //logic }));
You can sort a multidimensionnal array by any of its key with this function: function multi_sort($array, $key) { $cmp_val="((\$a['$key']>\$b['$key'])?1: ((\$a['$key']==\$b['$key'])?0:-1))"; $cmp=create_function('$a, $b', "return $body;"); uasort($array, $cmp); return $array; } example: $myarray = array( array("name"=>"kernighan", "language"=>"c"), array("name"=>"lerdorf", "language"=>"php"), array("name"=>"Stroustrup", "language"=>"c++"), array("name"=>"Gosling", "language"=>"java") ); multi_sort($myarray, "name") returns: name=Gosling language=java name=Kernighan language=c name=Lerdorf language=php name=Stroustrup language=c++
鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com
免责声明:我们致力于保护作者版权,注重分享,当前被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理!邮箱:344225443@qq.com)
图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!
内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)