PHP array_column 函数
最后修改于 2025 年 3 月 13 日
PHP array_column
函数从多维数组或对象数组中提取单个列。它对数据提取很有用。
基本定义
array_column
函数从输入数组中的单个列返回数值。它同时适用于数组和对象。
语法:array_column(array $array, mixed $column_key, mixed $index_key = null): array
。column_key
指定要提取的列。
array_column 基本示例
这展示了如何从关联数组数组中提取一列数值。
<?php $users = [ ['id' => 1, 'name' => 'John', 'email' => 'john@example.com'], ['id' => 2, 'name' => 'Mary', 'email' => 'mary@example.com'], ['id' => 3, 'name' => 'Peter', 'email' => 'peter@example.com'] ]; $names = array_column($users, 'name'); print_r($names);
这将从 users 数组中提取所有名称。输出将是一个包含 ['John', 'Mary', 'Peter'] 的数组。
使用索引键提取
您可以指定一个索引键用作结果数组中的键。
<?php $users = [ ['id' => 1, 'name' => 'John', 'email' => 'john@example.com'], ['id' => 2, 'name' => 'Mary', 'email' => 'mary@example.com'], ['id' => 3, 'name' => 'Peter', 'email' => 'peter@example.com'] ]; $emails = array_column($users, 'email', 'id'); print_r($emails);
这将创建一个以 ID 作为键,电子邮件作为值的数组。输出将是 [1 => 'john@example.com', 2 => 'mary@example.com', 3 => 'peter@example.com']。
使用对象
array_column 也可以从对象中提取公共属性。
<?php class User { public function __construct( public int $id, public string $name, public string $email ) {} } $users = [ new User(1, 'John', 'john@example.com'), new User(2, 'Mary', 'mary@example.com'), new User(3, 'Peter', 'peter@example.com') ]; $names = array_column($users, 'name'); print_r($names);
这将从每个 User 对象中提取 name 属性。输出将与第一个示例相同:['John', 'Mary', 'Peter']。
提取嵌套数据
array_column 可以使用点符号从嵌套数组中提取值。
<?php $products = [ ['id' => 1, 'details' => ['name' => 'Laptop', 'price' => 999]], ['id' => 2, 'details' => ['name' => 'Phone', 'price' => 699]], ['id' => 3, 'details' => ['name' => 'Tablet', 'price' => 399]] ]; $prices = array_column($products, 'details.price'); print_r($prices);
这将从嵌套的 details 数组中提取所有价格。输出将是 [999, 699, 399]。点符号访问嵌套的数组元素。
将 array_column 与 array_map 结合使用
将 array_column 与 array_map 结合使用,以进行更复杂的数据转换。
<?php $users = [ ['id' => 1, 'name' => 'John', 'email' => 'john@example.com'], ['id' => 2, 'name' => 'Mary', 'email' => 'mary@example.com'], ['id' => 3, 'name' => 'Peter', 'email' => 'peter@example.com'] ]; $formattedEmails = array_map( fn($email) => "Email: $email", array_column($users, 'email') ); print_r($formattedEmails);
这将提取电子邮件并使用前缀格式化它们。输出将是 ['Email: john@example.com', 'Email: mary@example.com', 'Email: peter@example.com']。
最佳实践
- 列存在性:在提取之前验证列是否存在。
- 性能:有效地用于大型数据集。
- 可读性:小心地与其他数组函数结合使用。
- 类型安全:提取值时考虑数据类型。
来源
本教程介绍了 PHP array_column
函数,并提供了实际示例,展示了它在数据提取场景中的用法。
作者
列出 所有 PHP 数组函数。