array_column()
是 PHP 5.5.0 及更高版本中的一个内置函数,它可以从多维数组或对象数组中提取一列数据
- 获取用户名称列表:
$users = [ ['id' => 1, 'name' => 'Alice'], ['id' => 2, 'name' => 'Bob'], ['id' => 3, 'name' => 'Charlie'] ]; $names = array_column($users, 'name'); print_r($names); // 输出: Array ( [0] => Alice [1] => Bob [2] => Charlie )
- 将用户ID作为键值:
$users = [ ['id' => 1, 'name' => 'Alice'], ['id' => 2, 'name' => 'Bob'], ['id' => 3, 'name' => 'Charlie'] ]; $names = array_column($users, 'name', 'id'); print_r($names); // 输出: Array ( [1] => Alice [2] => Bob [3] => Charlie )
- 从对象数组中提取属性:
class User {
public $id;
public $name;
public function __construct($id, $name) {
$this->id = $id;
$this->name = $name;
}
}
$users = [
new User(1, 'Alice'),
new User(2, 'Bob'),
new User(3, 'Charlie')
];
$names = array_column($users, 'name');
print_r($names); // 输出: Array ( [0] => Alice [1] => Bob [2] => Charlie )
- 根据指定的键值对数组进行分组:
$users = [ ['id' => 1, 'name' => 'Alice', 'group' => 'A'], ['id' => 2, 'name' => 'Bob', 'group' => 'B'], ['id' => 3, 'name' => 'Charlie', 'group' => 'A'] ]; $groups = array_column($users, null, 'group'); print_r($groups); /* 输出: Array ( [A] => Array ( [id] => 3 [name] => Charlie [group] => A ) [B] => Array ( [id] => 2 [name] => Bob [group] => B ) ) */
这些示例展示了如何使用 array_column()
函数处理不同类型的数组和对象。通过这个函数,你可以轻松地从复杂的数组结构中提取所需的数据。