PHP – ksort, asort, usort 用法

ksort, asort, usort 用法

PHP basic function,ksort, asort, usort,有幾種方式對陣列做排序,也用簡單的舉例來介紹吧!

  • ksort
  • asort
  • usort

sort

$array = [   'p3'=>'omg',   'c3'=>'charlie',   'p4'=>'site',   'p5'=>'poe',   's'=>'flame totem',   'd'=> 'day' ]; print_r(sort($array));

Array(
  [0] => omg
  [1] => charlie
  [2] => site
  [3] => poe
  [4] => flame totem
  [5] => day
)


ksort

ksort — 陣列鍵名排序
bool ksort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

print_r(ksort($array));

Array
(
  [c3] => charlie
  [d] => day
  [p3] => omg
  [p4] => site
  [p5] => poe
  [s] => flame totem
)


asort

asort – 對陣列進行排序並維護索引關聯
bool asort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

print_r(asort($array));

Array
(
  [c3] => charlie
  [d] => day
  [s] => flame totem
  [p3] => omg
  [p5] => poe
  [p4] => site
)


usort

usort – 定義的比較函數按值對陣列進行排序
bool usort ( array &$array , callable $value_compare_func )

function cmp($a, $b){
  if($a == $b){
    return 0;
  }
  return ($a < $b) ? -1 : 1;
}
$a = array(3, 2, 5, 6, 1);
usort($a, "cmp");
foreach ($a as $key => $value){
  echo "$key: $value\n";
}

0: 1
1: 2
2: 3
3: 5
4: 6

一起討論吧