目录

PHP array_column() 函数

❮ PHP 数组参考

示例

从记录集中获取姓氏列:

<?php
// An array that represents a possible record set returned from a database
$a = array(
  array(
    'id' => 5698,
    'first_name' => 'Peter',
    'last_name' => 'Griffin',
  ),
  array(
    'id' => 4767,
    'first_name' => 'Ben',
    'last_name' => 'Smith',
  ),
  array(
    'id' => 3809,
    'first_name' => 'Joe',
    'last_name' => 'Doe',
  )
);

$last_names = array_column($a, 'last_name');
print_r($last_names);
?>

输出:

Array
(
  [0] => Griffin
  [1] => Smith
  [2] => Doe
)


定义和用法

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


语法

array_column( array, column_key, index_key)

参数值

Parameter Description
array Required. Specifies the multi-dimensional array (record-set) to use. As of PHP 7.0, this can also be an array of objects.
column_key Required. An integer key or a string key name of the column of values to return. This parameter can also be NULL to return complete arrays (useful together with index_key to re-index the array)
index_key Optional. The column to use as the index/keys for the returned array


技术细节

返回值: 返回表示输入数组中单个列的值数组
PHP 版本: 5.5+

更多示例

示例

从记录集中获取姓氏列,按 "id" 列索引:

<?php
// An array that represents a possible record set returned from a database
$a = array(
  array(
    'id' => 5698,
    'first_name' => 'Peter',
    'last_name' => 'Griffin',
  ),
  array(
    'id' => 4767,
    'first_name' => 'Ben',
    'last_name' => 'Smith',
  ),
  array(
    'id' => 3809,
    'first_name' => 'Joe',
    'last_name' => 'Doe',
  )
);

$last_names = array_column($a, 'last_name', 'id');
print_r($last_names);
?>

输出:

Array
(
  [5698] => Griffin
  [4767] => Smith
  [3809] => Doe
)


❮ PHP 数组参考