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']
$users = User::all()->toArray(); // 假設從 ORM 取得
$userMap = array_column($users, null, 'id'); // 鍵為 id
// 之後 O(1) 查找
$userName = $userMap[$targetId]['name'] ?? 'Unknown';
$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;
}, []);
<?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+) 或警告