百科狗-知识改变命运!
--

uksort() - 使用用户自定义的比较函数对数组中的键名进行排序 - php 数组函数

梵高1年前 (2023-11-21)阅读数 18#技术干货
文章标签函数

uksort()

uksort() - 使用用户自定义的比较函数对数组中的键名进行排序 - php 数组函数

(PHP 4, PHP 5, PHP 7)

使用用户自定义的比较函数对数组中的键名进行排序

说明

uksort(array &$array,callable$key_compare_func): bool

uksort()函数将使用用户提供的比较函数对数组中的键名进行排序。如果要排序的数组需要用一种不寻常的标准进行排序,那么应该使用此函数。

Note:

If two members compare as equal, their relative order in the sorted array is undefined.

参数

$array

输入的数组。

$key_compare_func

在第一个参数小于,等于或大于第二个参数时,该比较函数必须相应地返回一个小于,等于或大于 0 的整数。

callback(mixed $a,mixed $b): int

返回值

成功时返回TRUE,或者在失败时返回FALSE

范例

Example #1uksort()例子

以上例程会输出:

an apple: 3
a banana: 4
the Earth: 2
John: 1

参见

  • usort() 使用用户自定义的比较函数对数组中的值进行排序
  • 数组排序函数对比
[Editor's note: the following comment may be factually incorrect]
uksort is only usable in the UK 
(about sorting an array of objects by their properties in a class - inspired by webmaster at zeroweb dot org at usort function)
I'm using classes as an abstraction for querying records in a database and use arrays of objects to store records that have an 1 to n relationship. E.g. a class "family" has family members stored as an array of objects. Each of those objects prepresents a record in a database related to the family (by it's familyId).
To identify members, I'm using their memberId as the key of the array e.g. $family->members[$memberId].
To sort the family members AFTER fetching them with the database query, you can use the functions _objSort and sortMembers which will sort the "members" array by key using it's properties (for space reasons I didn't include the methods used to open the records):

Note that this might not be the fastest thing on earth and it hasn't been tested very much yet but I hope it's useful for someone.
sort with collation, to have umlauts correctly:
uksort($retval, array(Collator::create( 'de_DE' ), 'compare'));
Case insensitive without own function:
uksort($array, "strnatcasecmp");
Here is a small and very fast object to handle sorting of multidimentional arrays by a key.

Sample $input_array:
Array
(
  [0] => Array
    (
      [id] => 961
      [uid] => 29
      [gid] => 12
      [parent_id] => 147
      [created] => 20041206105350
      [modified] => 20041206110702
    )
  [1] => Array
    (
      [id] => 41
      [uid] => 29
      [gid] => 12
      [parent_id] => 153
      [created] => 20041025154009
      [modified] => 20041206105532
    )
  [2] => Array
    (
      [id] => 703
      [uid] => 29
      [gid] => 12
      [parent_id] => 419
      [created] => 20041025154132
      [modified] => 20041027150259
    )
Example of usage:

The result array will be:
Array
(
  [0] => Array
    (
      [id] => 703
      [uid] => 29
      [gid] => 12
      [parent_id] => 419
      [created] => 20041025154132
      [modified] => 20041027150259
    )
  [1] => Array
    (
      [id] => 41
      [uid] => 29
      [gid] => 12
      [parent_id] => 153
      [created] => 20041025154009
      [modified] => 20041206105532
    )
  [2] => Array
    (
      [id] => 961
      [uid] => 29
      [gid] => 12
      [parent_id] => 147
      [created] => 20041206105350
      [modified] => 20041206110702
    )
Regarding the recursive sorting function above:
Genrally speaking, any recursion can be reimplemented using simple iteration. in the specific case, using recursion to compare strings has a huge performance impact while a simple loop would suffice and be faster and more simple. 
Recursion is only good if it simplifies your code or your understanding of the concept. the previous example does neither, especially as it does a lot of repetitive things in each iteration, such as asigning the character order constant, rebuilding it into an array and such
For example, the string comparison could be written as such : 
function str_compare($a,$b) {
  $order="aAbBcCčČ..."; // longer normally & without that html entities
  $default = strlen($a) - strlen($b);
  $minlen = strlen($a) 
The code below allows you to sort an array_A following array_B keys order, original keys and values remain associated.

Will print :
Array ( [age] => 19 [ville] => rennes [website] => kik-it.com [region] => bretagne [code_postal] => 35200 [Nom] => Fred ) 
Array ( [Nom] => Fred [age] => 19 [region] => bretagne [ville] => rennes [code_postal] => 35200 [website] => kik-it.com ) 
The keys not listed in the $TheArrayOrder will appear at the end of your sorted array (only if Key Pos 
One remark regarding array_sorter class.
It won't work correctly with eg. dates from mysql like 20041206105350, cause you can't convert such number into integer. To fix it remove intval() from the code. If the variable is a number it will work without converting this to int anyways. Here is the fix. 
To sort dates with uksort:
function datediff($a, $b) {
  
$a = date('U',$a);
$b = date('U',$b);
if ($a == $b) $r = 0;
else $r = ($a > $b) ? 1: -1;
return $r;
}
need a case insensitive sort by key function? i did and couldn find it, so: 
If you need to periodically sort by grades (A, A+, D-, etc.), here is a compare function that compares strings by the case-insensitive method, unless it finds a grade, in which case it correctly sorts by putting "plus" grades first, unmarked grades second, and "minus" grades last.

result: Array
(
  [A+] => 1
  [A-] => 5
  [B+] => 7
  [B] => 4
  [B-] => 4
  [C+] => 13
  [C] => 10
  [C-] => 6
  [D+] => 8
  [D] => 3
  [D-] => 3
  [F] => 5
)
Don't use uksort($array, "strnatcasecmp"); ... use ksort($array, SORT_NATURAL|SORT_FLAG_CASE);
I needed to be able to sort a string that contained numbers eg.
"Slot 1 name"
"Slot 2 name"
"Slot 10 name"
using a normal string compare the "Slot 10 name" would appear before "Slot 2 name" so I wrote little function that will compare a string taking numbers in to consideration. There may be a few edge cases that need to be taken in to consideration.
function strCmpWithNumbers( $a, $b) {
 // Split the string in to words.
 $a = explode(' ',$a);
 $b = explode(' ',$b);
 $loop = 0;
 do {
  // Get the first word from each item
  $ta = Utils::gvfa($a, $loop);
  $tb = Utils::gvfa($b, $loop);
  
  if (isset($ta)) {
   if (isset($tb)) {
    if (is_numeric($ta)) {
     if ($ta != $tb) {
      return $ta - $tb;
     }
    } else {
     $val = strcasecmp($ta, $tb);
     if ($val != 0) {
      return $val;
     }
    }
   } else {
    return 1; // a is set but b isn't
   }
  } else {
   return isset($b);
  }
  $loop +=1;
 } while (true);
}
An associative array with known keys can be easily custom sorted using a switch statement in the callback:
NB ksort can be used beforehand to ensure expected results
ksort($array);
uksort($array, function ($a) {          
  switch($a) {
    case 'pepperoni':
      return 0;
    case 'beef':
      return 1;
    case 'chicken':
      return 2;
    case 'ham':
      return 3;
    case 'vegetarian':
      return 4;
  }
});
...
function cmp($a, $b)
{
  if ($a == $b) {
    return 0;
  }
  return ($a  $value )
  {
    if ( is_array ( $value ) )
    {
      // [PHP5] uksort_tree ( $value );
      uksort_tree ( $array[$key] );
    }
  }
  uksort( $array, "cmp" );
}
uksort_tree( $myEntryArray );
...
To use a more complicated comparison function, one can use a callback to a method of an object instance.
For example the following will take an array $arr whose keys are the same as those of $reference, and reorder $arr so that the keys appear in the same order as in $reference.
class kcmp {
  var $reference ;
  function kcmp( $reference ) {
    $this->reference = $reference ; 
  }
  function kcompare( $a, $b ) {
    $keys = array_keys( $this->reference ) ;
    $position_a = array_search( $a, $keys ) ;
    $position_b = array_search( $b, $keys ) ;
    return $position_a  "a2",
  "k3" => "a3",
  "k1" => "a1"
) ;
$arr = array(
  "k1" => "b1",
  "k2" => "b2",
  "k3" => "b3"
) ;
print_r( $arr ) ; 
uksort( $arr, array( new kcmp( $reference ), "kcompare" ) ) ;
print_r( $arr ) ;

鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com

免责声明:我们致力于保护作者版权,注重分享,当前被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理!邮箱:344225443@qq.com)

图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)