rhumsaa/array_column

此包已被废弃,不再维护。作者建议使用 ramsey/array_column 包。

为使用 PHP 5.5 以下版本的项目提供 array_column() 功能。

1.1.3 2015-03-20 22:07 UTC

This package is auto-updated.

Last update: 2022-02-01 12:24:14 UTC


README

Build Status Coverage Status Latest Stable Version Total Downloads Latest Unstable Version License

这个简单的库为低于 5.5 版本的 PHP 提供了 array_column() 功能。它在所有方面都模仿了内置函数的功能。

用法

array array_column(array $input, mixed $columnKey[, mixed $indexKey])

给定一个多维数组,array_column() 返回输入数组中单个列的值,通过 $columnKey 标识。可选地,您可以提供一个 $indexKey,以根据输入数组中 $indexKey 列的值对返回数组中的值进行索引。

例如,使用以下数据数组,我们告诉 array_column() 返回一个仅包含姓氏的数组,并按记录 ID 索引。

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

$lastNames = array_column($records, 'last_name', 'id');

如果我们对 $lastNames 调用 print_r(),你将看到如下类似的数组

Array
(
    [2135] => Doe
    [3245] => Smith
    [5342] => Jones
    [5623] => Doe
)

安装

安装此库最简单的方法是使用 Composer

php composer.phar require ramsey/array_column

然后,当你运行 composer install 时,一切都将神奇地就位,并且只要包含 Composer 的自动加载器,array_column() 函数将可用于你的项目。

但是,您不需要 Composer 来使用此库。

此库没有依赖项,应在旧版本的 PHP 上正常工作。下载代码,并在您的项目中包含 src/array_column.php,一切应该正常。

当您准备在 PHP 5.5 上运行您的项目时,即使此库包含在您的项目中,一切也应该继续顺利运行,而不会有冲突。