php array_column
时间: 2023-07-31 13:05:29 浏览: 41
`array_column()` 是 PHP 中一个常用的数组函数,用于返回一个数组中指定键对应的值组成的新数组。
语法如下:
```php
array_column(array $input, mixed $column_key [, mixed $index_key = null ]);
```
参数说明:
- `$input`:要取出列的多维数组,必需。
- `$column_key`:需要返回值的列,可以是索引数组的下标,也可以是关联数组中的键名,必需。
- `$index_key`:作为返回数组的索引的列,可以是索引数组的下标,也可以是关联数组中的键名,可选。
示例:
```php
// 索引数组
$students = array(
array('name' => 'Tom', 'age' => 18),
array('name' => 'Jerry', 'age' => 20),
array('name' => 'Mickey', 'age' => 22)
);
// 取出 $students 数组中所有学生的姓名
$names = array_column($students, 'name');
print_r($names);
// 关联数组
$fruit = array(
array('name' => 'apple', 'color' => 'red', 'price' => 2.5),
array('name' => 'banana', 'color' => 'yellow', 'price' => 1.5),
array('name' => 'orange', 'color' => 'orange', 'price' => 3)
);
// 取出 $fruit 数组中所有水果的价格,并以水果的名称作为数组的索引
$prices = array_column($fruit, 'price', 'name');
print_r($prices);
```
输出结果:
```
Array
(
[0] => Tom
[1] => Jerry
[2] => Mickey
)
Array
(
[apple] => 2.5
[banana] => 1.5
[orange] => 3
)
```
在上面的示例中,我们分别使用了 `array_column()` 函数来取出多维数组中的指定列。在第一个示例中,我们取出了 `$students` 数组中所有学生的姓名,而在第二个示例中,我们取出了 `$fruit` 数组中所有水果的价格,并以水果的名称作为数组的索引。