處理 API 回傳、資料庫查詢結果、表單資料時,常需將關聯陣列(字串鍵)重排為 0 起始的連續數值索引陣列,以便 json_encode 輸出純陣列、array_values 語義化、或後續數值索引運算。
| 方法 | 程式碼 | 特點 | 適用場景 |
|---|---|---|---|
array_values() | $new = array_values($arr); | 內建函數、效能最佳、單層 | 最常用、單維陣列 |
array_merge() | $new = array_merge($arr); | 副作用重排、單層 | 快速單行 |
| 遞迴函數 | 自訂遞迴處理 | 支援多維陣列、保留結構 | 巢狀陣列重排 |
json_encode/decode | json_decode(json_encode($arr), true) | 連帶處理物件、資源型別 | 複雜結構轉純陣列 |
<?php
/**
* 遞迴將陣列所有層級鍵值重排為 0 起始數值索引
* @param array $array 輸入陣列
* @param bool $preserveKeys 是否保留原字串鍵(false=重排,true=保留)
* @return array 重排後陣列
*/
function array_reindex_recursive(array $array, $preserveKeys = false) {
$result = [];
foreach ($array as $key => $value) {
$newKey = $preserveKeys ? $key : null; // null 讓 PHP 自動分配數值索引
if (is_array($value)) {
$result[$newKey] = array_reindex_recursive($value, $preserveKeys);
} else {
$result[$newKey] = $value;
}
}
return $preserveKeys ? $result : array_values($result);
}
// 測試資料
$test = [
'a' => 1,
'b' => ['x' => 10, 'y' => 20],
'c' => 3,
'd' => ['m' => ['p' => 100], 'n' => 40]
];
echo "原陣列:\n";
print_r($test);
echo "\n重排後(單層 array_values):\n";
print_r(array_values($test));
echo "\n遞迴重排(多維):\n";
print_r(array_reindex_recursive($test));
/* 輸出結果:
遞迴重排(多維):
Array
(
[0] => 1
[1] => Array
(
[0] => 10
[1] => 20
)
[2] => 3
[3] => Array
(
[0] => Array
(
[0] => 100
)
[1] => 40
)
)
*/
/**
* 選擇性重排:僅重排指定深度或條件的鍵
* @param array $array
* @param int $depth 重排深度(0=全部,1=僅第一層,2=前兩層...)
* @param callable $condition 可選:自定條件函數 fn($key, $value, $depth) => bool
*/
function array_reindex_selective(array $array, $depth = 0, $condition = null, $currentDepth = 1) {
$result = [];
foreach ($array as $key => $value) {
$shouldReindex = ($depth === 0 || $currentDepth <= $depth)
&& (!$condition || $condition($key, $value, $currentDepth));
$newKey = $shouldReindex ? null : $key;
if (is_array($value)) {
$result[$newKey] = array_reindex_selective($value, $depth, $condition, $currentDepth + 1);
} else {
$result[$newKey] = $value;
}
}
return $shouldReindex ? array_values($result) : $result;
}
// 僅重排前兩層
print_r(array_reindex_selective($test, 2));
// 僅重排數值鍵的子陣列
print_r(array_reindex_selective($test, 0, fn($k,$v)=>is_int($k)));
<?php
$largeArr = [];
for ($i = 0; $i < 10000; $i++) {
$largeArr["key_$i"] = range(1, 10); // 10萬元素
}
$start = microtime(true);
$r1 = array_values($largeArr);
echo "array_values: " . (microtime(true) - $start) * 1000 . " ms\n";
$start = microtime(true);
$r2 = array_merge($largeArr);
echo "array_merge: " . (microtime(true) - $start) * 1000 . " ms\n";
$start = microtime(true);
$r3 = json_decode(json_encode($largeArr), true);
echo "json encode/decode: " . (microtime(true) - $start) * 1000 . " ms\n";
/* 典型輸出(單位 ms):
array_values: 1.2
array_merge: 1.5
json encode/decode: 45.8
*/
array_values() 僅重排第一層,巢狀陣列鍵名保持不變json_encode 會將資源型別、物件轉為空物件 {},可能導致資料遺失array_values(),最快最標準array_reindex_recursive()json_encode/decode 但注意型別損失