萬盛學電腦網

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

PHP 陣列鍵值重排:將關聯陣列轉為數值索引陣列的多種方法

需求場景

處理 API 回傳、資料庫查詢結果、表單資料時,常需將關聯陣列(字串鍵)重排為 0 起始的連續數值索引陣列,以便 json_encode 輸出純陣列、array_values 語義化、或後續數值索引運算。

方法對比

方法程式碼特點適用場景
array_values()$new = array_values($arr);內建函數、效能最佳、單層最常用、單維陣列
array_merge()$new = array_merge($arr);副作用重排、單層快速單行
遞迴函數自訂遞迴處理支援多維陣列、保留結構巢狀陣列重排
json_encode/decodejson_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 但注意型別損失
  • 選擇性重排:根據業務需求自訂邏輯
copyright © 萬盛學電腦網 all rights reserved