array_column()
函數(shù)用于從多維數(shù)組中提取一列數(shù)據(jù)
以下是使用 array_column()
處理多維數(shù)組的一些技巧:
$data = [
['id' => 1, 'name' => 'Alice'],
['id' => 2, 'name' => 'Bob'],
['id' => 3, 'name' => 'Carol']
];
$names = array_column($data, 'name');
print_r($names); // Output: Array ( [0] => Alice [1] => Bob [2] => Carol )
$data = [
['id' => 1, 'name' => 'Alice'],
['id' => 2, 'name' => 'Bob'],
['id' => 3, 'name' => 'Carol']
];
$names = array_column($data, 'name', 'id');
print_r($names); // Output: Array ( [1] => Alice [2] => Bob [3] => Carol )
$data = [
['id' => 1, 'name' => 'Alice', 'age' => 30],
['id' => 2, 'name' => 'Bob', 'age' => 25],
['id' => 3, 'name' => 'Carol', 'age' => 22]
];
$result = array_map(function ($item) {
return array_column($item, ['name', 'age']);
}, $data);
print_r($result);
/*
Output:
Array
(
[0] => Array ([name] => Alice [age] => 30)
[1] => Array ([name] => Bob [age] => 25)
[2] => Array ([name] => Carol [age] => 22)
)
*/
array_column()
與其他數(shù)組函數(shù)結(jié)合:$data = [
['id' => 1, 'name' => 'Alice', 'age' => 30],
['id' => 2, 'name' => 'Bob', 'age' => 25],
['id' => 3, 'name' => 'Carol', 'age' => 22]
];
$ages = array_column($data, 'age');
$averageAge = array_sum($ages) / count($ages);
echo $averageAge; // Output: 26.666666666667
通過這些技巧,您可以更有效地使用 array_column()
函數(shù)處理多維數(shù)組。