溫馨提示×

php array_column()處理多維數(shù)組技巧

PHP
小樊
84
2024-09-05 01:51:07
欄目: 編程語言

array_column() 函數(shù)用于從多維數(shù)組中提取一列數(shù)據(jù)

以下是使用 array_column() 處理多維數(shù)組的一些技巧:

  1. 提取多維數(shù)組中的單列數(shù)據(jù):
$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 )
  1. 使用指定的鍵名作為新數(shù)組的鍵:
$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 )
  1. 提取多維數(shù)組中的多列數(shù)據(jù):
$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)
)
*/
  1. 使用 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ù)組。

0