温馨提示×

如何处理array_column返回值

小樊
81
2024-12-11 03:34:11
栏目: 编程语言

array_column() 函数用于从数组中提取一个列,并作为新数组返回

  1. 使用foreach循环遍历数组:
$array = [
    ['name' => 'John', 'age' => 30],
    ['name' => 'Jane', 'age' => 28],
    ['name' => 'Doe', 'age' => 25],
];

$column_name = 'name';
$column_values = array_column($array, $column_name);

foreach ($column_values as $value) {
    echo $value . PHP_EOL;
}
  1. 使用array_map函数处理数组:
$array = [
    ['name' => 'John', 'age' => 30],
    ['name' => 'Jane', 'age' => 28],
    ['name' => 'Doe', 'age' => 25],
];

$column_name = 'name';
$column_values = array_column($array, $column_name);

$new_array = array_map(function ($item) use ($column_name) {
    return $item[$column_name];
}, $array);

print_r($new_array);
  1. 使用array_reduce函数处理数组:
$array = [
    ['name' => 'John', 'age' => 30],
    ['name' => 'Jane', 'age' => 28],
    ['name' => 'Doe', 'age' => 25],
];

$column_name = 'name';
$column_values = array_column($array, $column_name);

$new_array = array_reduce($array, function ($carry, $item) use ($column_name) {
    $carry[] = $item[$column_name];
    return $carry;
}, []);

print_r($new_array);

这些示例展示了如何使用不同的方法处理array_column()返回值。你可以根据自己的需求选择合适的方法。

0