萬盛學電腦網

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

PHP 5.5+ 核心陣列新函式 array_column() 完整解析與低版本 Polyfill 實作

PHP 5.5 引入 array_column(),單行解決「從多維陣列提取單一欄位」的高頻需求。本文詳細說明參數用法、實戰範例,並提供 PHP 5.3/5.4 相容的 Polyfill 實作。

函式簽名

array_column(array $array, int|string $column_key, int|string|null $index_key = null): array
  • $column_key:要提取的欄位鍵名(字串)或索引(整數)
  • $index_key:可選,作為結果陣列鍵名的欄位(字串鍵名或數字索引)

核心範例

<?php
$records = [
    ['id' => 2135, 'first_name' => 'John', 'last_name' => 'Doe'],
    ['id' => 3245, 'first_name' => 'Sally', 'last_name' => 'Smith'],
    ['id' => 5342, 'first_name' => 'Jane', 'last_name' => 'Jones'],
    ['id' => 5623, 'first_name' => 'Peter', 'last_name' => 'Doe'],
];

// 1. 基本提取:取得所有 first_name
$firstNames = array_column($records, 'first_name');
// ['John', 'Sally', 'Jane', 'Peter']

// 2. 指定 index_key:以 id 作為鍵
$indexedById = array_column($records, 'first_name', 'id');
// [2135 => 'John', 3245 => 'Sally', 5342 => 'Jane', 5623 => 'Peter']

// 3. 提取整行(省略 column_key 或用 null)
$fullRows = array_column($records, null, 'id');
// [2135 => ['id'=>2135,'first_name'=>'John',...], ...]

// 4. 數字索引陣列(如資料庫 fetch_all(MYSQLI_NUM) 結果)
$numericRecords = [
    [2135, 'John', 'Doe'],
    [3245, 'Sally', 'Smith'],
];
$names = array_column($numericRecords, 1); // 索引 1 對應 first_name
// ['John', 'Sally']

實戰應用場景

場景一:建立 ID → Model 映射表(快速查找)

$users = User::all()->toArray(); // 假設從 ORM 取得
$userMap = array_column($users, null, 'id'); // 鍵為 id
// 之後 O(1) 查找
$userName = $userMap[$targetId]['name'] ?? 'Unknown';

場景二:表單選項產生(value => label)

$categories = Category::pluck('name', 'id')->toArray();
// 等同於
$categories = array_column(Category::all()->toArray(), 'name', 'id');
// 輸出:[1 => '前端', 2 => '後端', 3 => '資料庫']
// Blade: 

場景三:資料轉換與分組


// 將記錄按分類分組
$grouped = [];
foreach ($records as $rec) {
    $grouped[$rec['category_id']][] = $rec;
}
// 等價於(PHP 5.5+)
$grouped = array_reduce($records, function($carry, $item) {
    $carry[$item['category_id']][] = $item;
    return $carry;
}, []);

Polyfill:PHP 5.3/5.4 相容實作

<?php
if (!function_exists('array_column')) {
    /**
     * Polyfill for array_column (PHP 5.5+)
     * @param array $input
     * @param int|string $columnKey
     * @param int|string|null $indexKey
     * @return array
     */
    function array_column(array $input, $columnKey, $indexKey = null) {
        $result = [];
        $columnKeyIsInt = is_int($columnKey);
        $indexKeyIsInt = $indexKey !== null && is_int($indexKey);
        
        foreach ($input as $key => $row) {
            // 取得目標值
            if ($columnKeyIsInt) {
                $val = isset($row[$columnKey]) ? $row[$columnKey] : null;
            } else {
                $val = isset($row[$columnKey]) ? $row[$columnKey] : null;
            }
            
            // 確定結果鍵名
            if ($indexKey !== null) {
                if ($indexKeyIsInt) {
                    $newKey = isset($row[$indexKey]) ? $row[$indexKey] : $key;
                } else {
                    $newKey = isset($row[$indexKey]) ? $row[$indexKey] : $key;
                }
                $result[$newKey] = $val;
            } else {
                $result[] = $val;
            }
        }
        return $result;
    }
}

效能與替代方案

方法PHP 版本效能可讀性
array_column()5.5+C 底層實作,最快⭐⭐⭐⭐⭐
array_map(fn($r) => $r['col'], $arr)5.3+較慢(呼叫回調開銷)⭐⭐⭐
foreach 手動建構所有接近 array_column⭐⭐
array_reduce()5.3+中等⭐⭐

常見陷阱

  • $index_key 值重複時,後者覆蓋前者(不報錯)
  • 輸入非陣列會拋出 TypeError (PHP 8+) 或警告
  • 多維陣列僅提取第一層,巢狀結構需遞迴處理
copyright © 萬盛學電腦網 all rights reserved