从记录集中取出 last_name 列:
$a = [
[
'id' => 5698,
'first_name' => 'Peter',
'last_name' => 'Griffin',
],
[
'id' => 4767,
'first_name' => 'Ben',
'last_name' => 'Smith',
],
[
'id' => 3809,
'first_name' => 'Joe',
'last_name' => 'Doe',
],
];
$last_names = array_column($a, 'last_name');
dump($last_names);
array(3) {
[0] => string(7) "Griffin"
[1] => string(5) "Smith"
[2] => string(3) "Doe"
}
array_column() 返回输入数组中某个单一列的值。
array_column(array,column_key,index_key);
参数 | 描述 |
---|---|
array | 必需。指定要使用的多维数组(记录集)。 |
column_key | 必需。需要返回值的列。可以是索引数组的列的整数索引,或者是关联数组的列的字符串键值。该参数也可以是 NULL,此时将返回整个数组(配合index_key 参数来重置数组键的时候,非常管用)。 |
index_key | 可选。作为返回数组的索引/键的列。 |
返回值: | 返回一个数组,数组的值为输入数组中某个单一列的值。 |
PHP 版本: | 5.5+ |
从记录集中取出 last_name 列,用相应的 "id" 列作为键值
$a = [
[
'id' => 5698,
'first_name' => 'Peter',
'last_name' => 'Griffin',
],
[
'id' => 4767,
'first_name' => 'Ben',
'last_name' => 'Smith',
],
[
'id' => 3809,
'first_name' => 'Joe',
'last_name' => 'Doe',
],
];
$last_names = array_column($a, 'last_name', 'id');
dump($last_names);
array(3) {
[5698] => string(7) "Griffin"
[4767] => string(5) "Smith"
[3809] => string(3) "Doe"
}
重置数组键名
$a = [
[
'id' => 5698,
'first_name' => 'Peter',
'last_name' => 'Griffin',
],
[
'id' => 4767,
'first_name' => 'Ben',
'last_name' => 'Smith',
],
[
'id' => 3809,
'first_name' => 'Joe',
'last_name' => 'Doe',
],
];
$last_names = array_column($a, null, 'id');
dump($last_names);
array(3) {
[5698] => array(3) {
["id"] => int(5698)
["first_name"] => string(5) "Peter"
["last_name"] => string(7) "Griffin"
}
[4767] => array(3) {
["id"] => int(4767)
["first_name"] => string(3) "Ben"
["last_name"] => string(5) "Smith"
}
[3809] => array(3) {
["id"] => int(3809)
["first_name"] => string(3) "Joe"
["last_name"] => string(3) "Doe"
}
}
如果数组是一维数组
$a = [
'id' => 5698,
'first_name' => 'Peter',
'last_name' => 'Griffin',
];
$last_names = array_column($a, null);
dump($last_names);
array(3) {
[0] => int(5698)
[1] => string(5) "Peter"
[2] => string(7) "Griffin"
}
$a = [
'id' => 5698,
'first_name' => 'Peter',
'last_name' => 'Griffin',
];
$last_names = array_column($a, 'id');
dump($last_names);
array(0) {
}
2023-07-25 更新