示例:
$users = [
['id' => 1, 'name' => 'Alice', 'age' => 25],
['id' => 2, 'name' => 'Bob', 'age' => 30],
['id' => 3, 'name' => 'Charlie', 'age' => 35]
];
$names = array_column($users, 'name');
// $names = ['Alice', 'Bob', 'Charlie']
示例:
$result = $db->query('SELECT id, name, age FROM users');
$users = $result->fetchAll(PDO::FETCH_ASSOC);
$names = array_column($users, 'name');
示例:
$options = [
['id' => 1, 'name' => 'Option 1'],
['id' => 2, 'name' => 'Option 2'],
['id' => 3, 'name' => 'Option 3']
];
$selectOptions = array_column($options, 'name', 'id');
// $selectOptions = [1 => 'Option 1', 2 => 'Option 2', 3 => 'Option 3']
示例:
class User {
public $id;
public $name;
public $age;
public function __construct($id, $name, $age) {
$this->id = $id;
$this->name = $name;
$this->age = $age;
}
}
$users = [
new User(1, 'Alice', 25),
new User(2, 'Bob', 30),
new User(3, 'Charlie', 35)
];
$names = array_column($users, 'name');