處理陣列時,常遇到鍵值混亂(如刪除元素後索引不連續、關聯陣列需轉為索引陣列)的情況。本文提供一個遞迴函式 restore_array(),能將任意多維陣列的鍵值重新排序為 0,1,2,3…,並保留巢狀結構。
function restore_array($arr) {
if (!is_array($arr)) {
return $arr;
}
$c = 0;
$new = [];
while (list($key, $value) = each($arr)) {
if (is_array($value)) {
$new[$c] = restore_array($value); // 遞迴處理子陣列
} else {
$new[$c] = $value;
}
$c++;
}
return $new;
}
$input = ['a' => 1, 'b' => 2, 'c' => ['x' => 10, 'y' => 20]];
$output = restore_array($input);
print_r($output);
/* 輸出:
Array
(
[0] => 1
[1] => 2
[2] => Array
(
[0] => 10
[1] => 20
)
)
*/
array_values()若僅需處理單層陣列,PHP 內建 array_values() 即可達到相同效果,且效能更佳:
$arr = ['a' => 1, 'b' => 2]; $indexed = array_values($arr); // [0 => 1, 1 => 2]
本文函式適用於多維陣列遞迴重置的進階需求。