萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 陣列排序函數家族完全解析:sort、rsort、asort、arsort、ksort、krsort 與實戰對比

六大核心排序函數對照

函數排序依據保留鍵名順序適用陣列類型
sort()值❌ 重建 0..n升序 (A-Z, 0-9)索引陣列
rsort()值❌降序 (Z-A, 9-0)索引陣列
asort()值✅升序關聯陣列
arsort()值✅降序關聯陣列
ksort()鍵名✅升序關聯陣列
krsort()鍵名✅降序關聯陣列

實戰範例

索引陣列:sort / rsort

<?php
$numbers = [2, 8, 10, 6];
sort($numbers);
print_r($numbers); // [0=>2, 1=>6, 2=>8, 3=>10] 索引重建

$numbers = [2, 8, 10, 6];
rsort($numbers);
print_r($numbers); // [0=>10, 1=>8, 2=>6, 3=>2]
?>

關聯陣列:asort / arsort (按值排序,保留鍵)

<?php
$full_name = [
    'Roger'   => 'Waters',
    'Richard' => 'Wright',
    'Nick'    => 'Mason',
    'David'   => 'Gilmour',
];

asort($full_name);  // 按姓氏升序
foreach ($full_name as $first => $last) {
    echo "$first $last\n";
}
/* 輸出:
David Gilmour
Nick Mason
Roger Waters
Richard Wright
*/

arsort($full_name); // 按姓氏降序
// Richard Wright, Roger Waters, Nick Mason, David Gilmour
?>

關聯陣列:ksort / krsort (按鍵排序)

<?php
$scores = [
    'Alice' => 85,
    'Bob'   => 92,
    'Charlie' => 78,
];

ksort($scores);   // 按名字升序
// Alice, Bob, Charlie

krsort($scores);  // 按名字降序
// Charlie, Bob, Alice
?>

進階排序:自然排序與多維陣列

<?php
// 自然排序:人類直覺順序
$files = ['img1.png', 'img10.png', 'img2.png', 'img20.png'];
sort($files);      // 標準:img1, img10, img2, img20 (字典序)
natsort($files);   // 自然:img1, img2, img10, img20
natcasesort($files); // 不分大小寫自然排序

// 多維陣列自訂排序
$products = [
    ['id'=>3, 'name'=>'Mouse',  'price'=>299],
    ['id'=>1, 'name'=>'Keyboard','price'=>799],
    ['id'=>2, 'name'=>'Monitor', 'price'=>3999],
];

// 按價格升序
usort($products, fn($a, $b) => $a['price'] <=> $b['price']);

// 按價格降序,價格相同按名稱升序
usort($products, function($a, $b) {
    $cmp = $b['price'] <=> $a['price']; // 降序
    return $cmp !== 0 ? $cmp : $a['name'] <=> $b['name'];
});

// 保留鍵名版
uasort($products, fn($a, $b) => $a['price'] <=> $b['price']);
?>

排序旗標 (第 2 參數)

旗標說明
SORT_REGULAR預設,一般比較 (數字<字串)
SORT_NUMERIC數值比較
SORT_STRING字串比較
SORT_LOCALE_STRING依當前 locale 比較 (需 setlocale)
SORT_NATURAL自然排序 (PHP 5.4+)
SORT_FLAG_CASE配合 STRING 忽略大小寫
<?php
$mixed = ['10', '2', '1a', '2a'];
sort($mixed, SORT_STRING);   // ['10', '1a', '2', '2a'] 字典序
sort($mixed, SORT_NUMERIC);  // ['2', '10', '1a', '2a'] 數值轉換比較
sort($mixed, SORT_NATURAL);  // ['2', '10', '1a', '2a'] 自然序
?>

常見錯誤與避坑

  • 對關聯陣列用 sort():會丟失鍵名關係,改用 asort()/ksort()
  • 多維陣列直接 sort():PHP 無法比較陣列,會拋出 Warning,需用 usort()
  • shuffle() 會重建索引,關聯陣列鍵名會丟失
  • 排序函數直接修改原陣列 (回傳 bool),若需保留原陣列請先 $copy = $arr
  • 大量資料排序考慮 SplHeap、SplPriorityQueue 或資料庫 ORDER BY
copyright © 萬盛學電腦網 all rights reserved