数组函数

PHP array_column() 函数

主题:PHP 数组参考上一页|下一页

说明

array_column() 函数返回输入数组中单列的值。

下表总结了该函数的技术细节。

返回值: 返回表示输入数组中单列的值数组。
变更日志: 从 PHP 7.0.0 开始,也可以使用对象数组。
版本: PHP 5.5.0+

语法

array_column() 函数的基本语法如下:

sort(array, column_key, index_key);

下面的例子展示了 array_column() 函数的作用。

<?php
// 样本数组
$movies = array(
    array(
        "id" => "1",
        "name" => "Titanic",
        "genre" => "Drama",
    ),
    array(
        "id" => "2",
        "name" => "Justice League",
        "genre" => "Action",
    ),
    array(
        "id" => "3",
        "name" => "Joker",
        "genre" => "Thriller",
    )
);

// 获取名称列
$names = array_column($movies, "name");
print_r($names);
?>

参数

array_column() 函数接受以下参数。

参数 说明
array 必填。 指定要处理的多维数组或对象数组。
column_key

必填。 指定要检索的列的索引或键名。

此参数也可以是 NULL 以返回完整的数组或对象(这与 index_key 参数一起用于重新索引数组)。
index_key 可选。 指定用作返回数组的索引/键的列。

更多示例

这里有更多示例展示了 array_column() 函数的实际工作原理:

以下示例演示如何从由"id"列值索引的电影数组中检索"name"列值。 您可以选择任何列进行索引。

<?php
// 样本数组
$movies = array(
    array(
        "id" => "1",
        "name" => "Titanic",
        "genre" => "Drama",
    ),
    array(
        "id" => "2",
        "name" => "Justice League",
        "genre" => "Action",
    ),
    array(
        "id" => "3",
        "name" => "Joker",
        "genre" => "Thriller",
    )
);

// 获取名称列
$names = array_column($movies, "name", "id");
print_r($names);
?>

以下示例从对象的公共"name"属性中获取名称列。

<?php
// 类定义
class Person
{
    public $name;

    public function __construct(string $name)
    {
        $this->name = $name;
    }
}

// 创建对象数组
$persons = [
    new Person("Peter"),
    new Person("Alice"),
    new Person("Clark"),
];

// 获取name列
$names = array_column($persons, "name");
print_r($names);
?>
Advertisements