温馨提示×

php pluck的典型用例有哪些

PHP
小樊
86
2024-08-03 08:46:09
栏目: 编程语言

  1. 从数组中提取指定键的值组成新的数组:
$data = [
    ['id' => 1, 'name' => 'Alice'],
    ['id' => 2, 'name' => 'Bob'],
    ['id' => 3, 'name' => 'Charlie']
];

$names = array_column($data, 'name');
print_r($names);
  1. 从对象数组中提取指定属性的值组成新的数组:
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);
  1. 从关联数组中提取指定键的值组成新的数组:
$data = [
    'id' => 1,
    'name' => 'Alice',
    'age' => 25
];

$values = array_values($data);
print_r($values);

0