array_column
(PHP 5 >= 5.5.0, PHP 7, PHP 8)
array_column — 返回輸入陣列中指定列的值
說明
$array
, int|string|null $column_key
, int|string|null $index_key
= null
): array
array_column() 返回
array
中鍵名為
column_key
的一列值。 如果指定了可選參數
index_key
,則使用輸入陣列中
index_key
列的值將作為返回陣列中對應值的鍵。
參數
-
array
-
多維陣列或對像陣列,從中提取一列值。 如果提供的是對像陣列,只有 public 的屬性會被直接取出。 如果想取出 private 和 protected 的屬性,類必須實現 __get() 和 __isset() 魔術方法。
-
column_key
-
需要返回值的列。它可以是索引陣列的列索引,或者是關聯陣列的列的鍵,也可以是屬性名。 也可以是
null
,此時將返回整個陣列(配合index_key
參數來重新索引陣列時非常好用)。 -
index_key
-
作為返回陣列的索引/鍵的列。它可以是該列的整數索引,或者字串鍵值。 該值會像陣列鍵一樣被 強制轉換 (但是,在 PHP 8.0.0 之前,也被允許支援轉換為字串對像)。
返回值
返回輸入陣列中單列值的陣列。
範例
示例 #1 從結果集中取出 first_name 列
<?php
// 表示從數據庫返回的記錄集的陣列
$records = array(
array(
'id' => 2135,
'first_name' => 'John',
'last_name' => 'Doe',
),
array(
'id' => 3245,
'first_name' => 'Sally',
'last_name' => 'Smith',
),
array(
'id' => 5342,
'first_name' => 'Jane',
'last_name' => 'Jones',
),
array(
'id' => 5623,
'first_name' => 'Peter',
'last_name' => 'Doe',
)
);
$first_names = array_column($records, 'first_name');
print_r($first_names);
?>
以上例程會輸出:
Array ( [0] => John [1] => Sally [2] => Jane [3] => Peter )
示例 #2 從結果集中總取出 last_name 列,用相應的「id」作為鍵值
<?php
// 使用示例 #1 中的 $records 陣列
$last_names = array_column($records, 'last_name', 'id');
print_r($last_names);
?>
以上例程會輸出:
Array ( [2135] => Doe [3245] => Smith [5342] => Jones [5623] => Doe )
示例 #3 username 列是從對像獲取 public 的 "username" 屬性
<?php
class User
{
public $username;
public function __construct(string $username)
{
$this->username = $username;
}
}
$users = [
new User('user 1'),
new User('user 2'),
new User('user 3'),
];
print_r(array_column($users, 'username'));
?>
以上例程會輸出:
Array ( [0] => user 1 [1] => user 2 [2] => user 3 )
示例 #4 通過 __get() 魔術方法從對像中獲取 private 屬性的 "name" 列。
<?php
class Person
{
private $name;
public function __construct(string $name)
{
$this->name = $name;
}
public function __get($prop)
{
return $this->$prop;
}
public function __isset($prop) : bool
{
return isset($this->$prop);
}
}
$people = [
new Person('Fred'),
new Person('Jane'),
new Person('John'),
];
print_r(array_column($people, 'name'));
?>
以上例程會輸出:
Array ( [0] => Fred [1] => Jane [2] => John )