array_column()
函数用于从多维数组中提取一列数据
以下是使用 array_column()
处理多维数组的一些技巧:
- 提取多维数组中的单列数据:
$data = https://www.yisu.com/ask/['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 = https://www.yisu.com/ask/['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 = https://www.yisu.com/ask/['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()
与其他数组函数结合:
$data = https://www.yisu.com/ask/['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()
函数处理多维数组。