uksort — Sort an array by keys using a user-defined comparison function
uksort是用来按照 用户自定义比较的函数,用于比较数组的键值大小 来排序一个数组。
bool uksort ( array &$array
, callable $cmp_function
) 返回值true(success) or false(failure);
The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
cmp_function比较函数必须返回一个小于等于或者大于0的值,对应于函数的第一个参数和第二个参数的大小比较值。
第一个参数大于第二个参数,返回值大于0代表 第二个参数相应键值的项往前排;
第一个参数小于第二个参数,返回值小于0代表 第二个参数相应键值的项往后排。
第一个例子:
<?php
function cmp($a, $b)
{
$a = preg_replace('@^(a|an|the) @', '', $a);
$b = preg_replace('@^(a|an|the) @', '', $b);
return strcasecmp($a, $b);
}
$a = array("John" => 1, "the Earth" => 2, "an apple" => 3, "a banana" => 4);
uksort($a, "cmp");
foreach ($a as $key => $value) {
echo "$key: $value\n";
}
?>
第二个例子:(摘自ecmall)
function cmp($a, $b) { if ($b == 'alipay')//返回值大于0:如果键值$b=='alipay'那么键值为alipay的往前排 { return 1; } elseif ($b == 'tenpay2' && $a != 'alipay')//返回值大于0,如果键值$b=='tenpay2',并且$a!==’alipay'那么键值为tenpay2的往前排 { return 1; } elseif ($b == 'tenpay' && $a != 'alipay' && $a != 'tenpay2')//同上 { return 1; } else { return -1; } } $payments=array('alipay'=>array('code'=>'alipay'),'bank'=>array('code'=>'bank'),'cod'=>array('code'=>'cod'),'post'=>array('code'=>'post'), 'tenpay'=>array('code'=>'tenpay'),'paypal'=>array('code'=>'paypal'),'tenpay2'=>array('code'=>'tenpay2')); uksort($payments, "cmp"); foreach ($payments as $key => $value) { echo $key.":\n"; var_dump($value); }