您的位置 首页 php

每天一个常用PHP函数-array_column

场景

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

语法

 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);  

文章来源:智云一二三科技

文章标题:每天一个常用PHP函数-array_column

文章地址:https://www.zhihuclub.com/80435.shtml

关于作者: 智云科技

热门文章

网站地图