array_column()
是 PHP 中的一个内置函数,它用于从二维数组或对象数组中提取一列值。这个函数需要传递两个参数:一个是输入的二维数组,另一个是需要提取的列的名称(键名)。
下面是 array_column()
函数的基本语法:
array_column(array $input, mixed $column_key[, mixed $index_key = null]);
$input
是你要处理的二维数组或对象数组。$column_key
是你想从每个数组中提取的列的键名。$index_key
是可选参数,如果指定了该参数,那么返回的数组将使用 $index_key
指定的列的值作为索引。下面是一个简单的示例,说明如何使用 array_column()
函数:
<?php
// 示例数组
$records = [
[
'id' => 1,
'name' => 'John',
'age' => 25
],
[
'id' => 2,
'name' => 'Jane',
'age' => 30
],
[
'id' => 3,
'name' => 'Mike',
'age' => 35
]
];
// 使用 array_column() 提取 name 列
$names = array_column($records, 'name');
print_r($names); // 输出: Array ( [0] => John [1] => Jane [2] => Mike )
// 使用 array_column() 提取 name 列,并以 id 作为索引
$namesWithIds = array_column($records, 'name', 'id');
print_r($namesWithIds); // 输出: Array ( [1] => John [2] => Jane [3] => Mike )
?>
在上面的示例中,我们首先创建了一个包含多个关联数组的索引数组 $records
。然后,我们使用 array_column()
函数分别提取了 name
列和 name
列(同时以 id
作为索引)。最后,我们使用 print_r()
函数打印了结果。