(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 的屬性會(huì )被直接取出。 如果想取出 private 和 protected 的屬性,類(lèi)必須實(shí)現 __get() 和 __isset() 魔術(shù)方法。
column_key
需要返回值的列。它可以是索引數組的列索引,或者是關(guān)聯(lián)數組的列的鍵,也可以是屬性名。
也可以是 null
,此時(shí)將返回整個(gè)數組(配合
index_key
參數來(lái)重新索引數組時(shí)非常好用)。
index_key
作為返回數組的索引/鍵的列。它可以是該列的整數索引,或者字符串鍵值。 該值會(huì )像數組鍵一樣被 強制轉換 (但是,在 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);
?>
以上例程會(huì )輸出:
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);
?>
以上例程會(huì )輸出:
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'));
?>
以上例程會(huì )輸出:
Array ( [0] => user 1 [1] => user 2 [2] => user 3 )
示例 #4 通過(guò) __get() 魔術(shù)方法從對象中獲取 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'));
?>
以上例程會(huì )輸出:
Array ( [0] => Fred [1] => Jane [2] => John )