溫馨提示×

php pluck的典型用例有哪些

PHP
小樊
86
2024-08-03 08:46:09
欄目: 編程語言

  1. 從數(shù)組中提取指定鍵的值組成新的數(shù)組:
$data = [
    ['id' => 1, 'name' => 'Alice'],
    ['id' => 2, 'name' => 'Bob'],
    ['id' => 3, 'name' => 'Charlie']
];

$names = array_column($data, 'name');
print_r($names);
  1. 從對象數(shù)組中提取指定屬性的值組成新的數(shù)組:
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. 從關(guān)聯(lián)數(shù)組中提取指定鍵的值組成新的數(shù)組:
$data = [
    'id' => 1,
    'name' => 'Alice',
    'age' => 25
];

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

0