PHP 5.5 引入 array_column(),極大簡化二維數組列提取。本文詳細說明語法、參數、多種用法,並提供低版本 PHP 兼容實現,助你無縫升級。
array_column(array $array, int|string $column_key, int|string|null $index_key = null): array
$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'],
];
$firstNames = array_column($records, 'first_name');
/*
Array (
[0] => John
[1] => Sally
[2] => Jane
[3] => Peter
)
*/
$records = [
[1, 'John', 'Doe'],
[2, 'Sally', 'Smith'],
[3, 'Jane', 'Jones'],
];
$lastNames = array_column($records, 2); // 索引 2
/*
Array (
[0] => Doe
[1] => Smith
[2] => Jones
)
*/
$mismatched = [
['a' => 'foo', 'b' => 'bar', 'e' => 'baz'],
['a' => 'qux', 'c' => 'quux', 'd' => 'corge'],
['a' => 'grault', 'b' => 'garply', 'e' => 'waldo'],
];
$foo = array_column($mismatched, 'a', 'b');
/*
Array (
[bar] => foo
[0] => qux // 第二行無 b 鍵,落回數字索引
[garply] => grault
)
*/
<?php
if (!function_exists('array_column')) {
function array_column(array $input, $columnKey, $indexKey = null) {
$result = [];
$colIsNum = is_numeric($columnKey);
$idxIsNull = is_null($indexKey);
$idxIsNum = is_numeric($indexKey);
foreach ($input as $key => $row) {
// 獲取列值
if ($colIsNum) {
$tmp = array_slice($row, $columnKey, 1);
$val = (is_array($tmp) && $tmp) ? current($tmp) : null;
} else {
$val = isset($row[$columnKey]) ? $row[$columnKey] : null;
}
// 確定新鍵
if (!$idxIsNull) {
if ($idxIsNum) {
$tmp = array_slice($row, $indexKey, 1);
$newKey = (is_array($tmp) && $tmp) ? current($tmp) : 0;
} else {
$newKey = isset($row[$indexKey]) ? $row[$indexKey] : 0;
}
} else {
$newKey = $key;
}
$result[$newKey] = $val;
}
return $result;
}
}
array_column($users, 'name', 'id') 直接得到 [id => name] 字典,省去循環array_map(fn($u) => $u['profile']['avatar'], $users) 再 array_column| PHP 版本 | 支援 | 備選 |
|---|---|---|
| >= 5.5.0 | 內建 | — |
| 5.3 - 5.4 | Polyfill | 上文自定義函數 |
| < 5.3 | 不支援 | foreach 手工構建 |
項目若已升級 PHP 5.5+,請直接使用內建函數,代碼更簡潔、性能更優(C 層實現)。