二維數組常用於存儲列表數據(如用戶列表、商品信息)。需按某字段(如 id、date、name)排序,再遍歷輸出。
提取排序鍵構建單獨數組,再同步排序主數組。
<?php
$data = [
['id' => 3, 'name' => 'Charlie', 'score' => 85],
['id' => 1, 'name' => 'Alice', 'score' => 92],
['id' => 2, 'name' => 'Bob', 'score' => 78],
];
// 按 score 降序
$scores = array_column($data, 'score');
array_multisort($scores, SORT_DESC, $data);
print_r($data);
/*
Array
(
[0] => Array ( [id] => 1 [name] => Alice [score] => 92 )
[1] => Array ( [id] => 3 [name] => Charlie [score] => 85 )
[2] => Array ( [id] => 2 [name] => Bob [score] => 78 )
)
*/
?>
優點: 內置函數、速度快、支持多鍵排序。缺點: 需額外構建鍵數組。
<?php
function sortByKey(array &$array, string $key, int $order = SORT_ASC) {
usort($array, function($a, $b) use ($key, $order) {
// 處理缺失鍵
if (!isset($a[$key]) || !isset($b[$key])) return 0;
$cmp = $a[$key] <=> $b[$key]; // PHP 7+ 太空船操作符
return $order === SORT_DESC ? -$cmp : $cmp;
});
}
$data = [
['id' => 3, 'date' => '2024-05-20'],
['id' => 1, 'date' => '2024-05-22'],
['id' => 2, 'date' => '2024-05-18'],
];
sortByKey($data, 'date', SORT_DESC); // 按日期降序
print_r($data);
?>
優點: 邏輯集中、可處理日期字符串、多級排序。缺點: 大數據量下比 array_multisort 慢。
<?php
$data = [
10 => ['name' => 'Item A', 'price' => 50],
5 => ['name' => 'Item B', 'price' => 30],
20 => ['name' => 'Item C', 'price' => 80],
];
// 提取價格並保持鍵名
$prices = [];
foreach ($data as $k => $v) $prices[$k] = $v['price'];
asort($prices); // 價格升序,鍵名不變
// 重組
$sorted = [];
foreach ($prices as $k => $v) $sorted[$k] = $data[$k];
print_r($sorted);
?>
<?php
// 1. foreach 引用修改(慎用,循環後 unset)
foreach ($data as &$row) {
$row['formatted_price'] = '¥' . number_format($row['price'], 2);
}
unset($row); // 打破引用
// 2. 只讀遍歷
foreach ($data as $row) {
echo "{$row['name']}: {$row['formatted_price']}
";
}
// 3. 帶索引
foreach ($data as $idx => $row) {
echo ($idx+1) . ". {$row['name']}
";
}
?>
| 方法 | 耗時(ms) | 記憶體 |
|---|---|---|
| array_multisort + array_column | ~45 | 低 |
| usort + 閉包 | ~120 | 中 |
| foreach + asort 重組 | ~80 | 高 |