定义和用法
array_column() 返回输入数组中某个单一列的值。
(PHP 5 >= 5.5.0, PHP 7, PHP 8)
语法
array_column(array,column_key,index_key);
| 参数 | 描述 |
|---|---|
| array | 必需。规定要使用的多维数组(记录集)。如果提供的是包含一组对象的数组,只有 public 属性会被直接取出。 为了也能取出 private 和 protected 属性,类必须实现 __get() 和 __isset() 魔术方法。 如果不提供__isset(),会返回空数组 |
| column_key | 必需。需要返回值的列。 可以是索引数组的列的整数索引,或者是关联数组的列的字符串键值。 该参数也可以是 NULL,此时将返回整个数组(配合 index_key 参数来重置数组键的时候,非常有用)。 |
| index_key | 可选。用作返回数组的索引/键的列。 |
示例
1,从记录集中取出 last_name 列:
<?php// 表示由数据库返回的可能记录集的数组$a = array(array('id' => 5698,'first_name' => 'Bill','last_name' => 'Gates',),array('id' => 4767,'first_name' => 'Steve','last_name' => 'Jobs',),array('id' => 3809,'first_name' => 'Mark','last_name' => 'Zuckerberg',));$last_names = array_column($a, 'last_name');print_r($last_names);?>

2,从记录集中取出 last_name 列,用相应的 “id” 列作为键值:
<?php// 表示由数据库返回的可能记录集的数组$a = array(array('id' => 5698,'first_name' => 'Bill','last_name' => 'Gates',),array('id' => 4767,'first_name' => 'Steve','last_name' => 'Jobs',)array('id' => 3809,'first_name' => 'Mark','last_name' => 'Zuckerberg',));$last_names = array_column($a, 'last_name', 'id');print_r($last_names);?>

3,username 列是从对象获取 public 的 “username” 属性
<?phpclass 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'));?>

4,获取 username 列,从对象通过魔术方法 __get() 获取 private 的 “username” 属性。
<?phpclass 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'));?>

如果不提供__isset(),会返回空数组。
4,取某一列为键,整个数组对象为值组成
<?php/*** Created by PhpStorm* User: darry* Date: 2021/2/22* Time: 15:05*/class A{public $name;public $value;public function __construct($name,$value){$this->name = $name;$this->value = $value;}}$arr = [new A(1,2),new A("ss",2),new A("haha",2),];$arr2 = array_column($arr,null,"name");print_r($arr2);

