场景

当我们通过api或者db获取到一个用户列表时,如果想按照id进行分组如何做?当然可以通过db的groupBy直接返回,如果是api获取呢?对用户列表进行foreach吗,太low了,答案便是array_column。

语法

phplist数组天天一个常用PHP函数arraycolumn jQuery

array_column ( array $input , mixed $column_key [, mixed $index_key = NULL ] ) : array$input是要处理的数组, $column_key是须要从数组中获取的字段, 可以是单个字段如'id',可以是null这时获取的是全体数组,可以是部分字段['id', 'name']$index_key则是新数组的索引, 是数值或者字符串

利用

<?php$userList = [ ['id' => 1, 'name' => '快乐的鸟', 'totalAmount' => 1000], ['id' => 3, 'name' => '愤怒的鸟', 'totalAmount' => 10], ['id' => 100, 'name' => '忧伤的鸟', 'totalAmount' => 100], ['id' => 55, 'name' => '勤奋的鸟', 'totalAmount' => 3000]];$userList = array_column($userList, null, 'id');print_r($userList);/Array( [1] => Array ( [id] => 1 [name] => 快乐的鸟 [totalAmount] => 1000 ) [3] => Array ( [id] => 3 [name] => 愤怒的鸟 [totalAmount] => 10 ) [100] => Array ( [id] => 100 [name] => 忧伤的鸟 [totalAmount] => 100 ) [55] => Array ( [id] => 55 [name] => 勤奋的鸟 [totalAmount] => 3000 ))/

如果只须要获取id与totalAmount该怎么获取呢,只须要加上$column_key就可以了

<?php$userList = array_column($userList, 'totalAmount', 'id');print_r($userList);/Array( [1] => 1000 [3] => 10 [100] => 100 [55] => 3000)/

当然如果数组的元素是工具也是可以取到工具的属性值

class User { public $id; public $name; public function __construct(int $id, string $name) { $this->id = $id; $this->name = $name; }}$userList = [ new User(1, '快乐的鸟'), new User(2, '愤怒的鸟'), new User(3, '勤奋的鸟')];$userList = array_column($userList, 'name', 'id');print_r($userList);