Latest web development tutorials

PHP array_column () function

PHP Array Reference Complete PHP Array Reference

Examples

Remove last_name columns from the centralized record:

<?php
// 可能从数据库中返回数组
$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);
?>

Output:

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


Definition and Usage

array_column () Returns the value of a single input array column.


grammar

array_column( array , column_key , index_key );

参数 描述
array 必需。指定要使用的多维数组(记录集)。
column_key 必需。需要返回值的列。可以是索引数组的列的整数索引,或者是关联数组的列的字符串键值。该参数也可以是 NULL,此时将返回整个数组(配合index_key 参数来重置数组键的时候,非常管用)。
index_key 可选。作为返回数组的索引/键的列。

technical details

return value: It returns an array of input value is an array of arrays in a single column.
PHP version: 5.5+


More examples

Example 1

Remove last_name columns from the centralized record, with the corresponding "id" column as key:

<?php
// 可能从数据库中返回数组
$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);
?>

Output:

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



PHP Array Reference Complete PHP Array Reference