PHP发布了其中增加了一个新的数组函数array_column感觉不错的!但是低版本PHP要使用得自己实现
参考地址
复制代码 代码如下:
if(!function_exists(
array_column
)){
function array_column($input
$columnKey
$indexKey=null){
$columnKeyIsNumber = (is_numeric($columnKey)) ? true : false;
$indexKeyIsNull = (is_null($indexKey)) ? true : false;
$indexKeyIsNumber = (is_numeric($indexKey)) ? true : false;
$result = array();
foreach((array)$input as $key=>$row){
if($columnKeyIsNumber){
$tmp = array_slice($row
$columnKey
);
$tmp = (is_array($tmp) && !empty($tmp)) ? current($tmp) : null;
}else{
$tmp = isset($row[$columnKey]) ? $row[$columnKey] : null;
}
if(!$indexKeyIsNull){
if($indexKeyIsNumber){
$key = array_slice($row
$indexKey
);
$key = (is_array($key) && !empty($key)) ? current($key) : null;
$key = is_null($key) ?
: $key;
}else{
$key = isset($row[$indexKey]) ? $row[$indexKey] :
;
}
}
$result[$key] = $tmp;
}
return $result;
}
}
// 使用例子
$records = array(
array(
id
=>
first_name
=>
John
last_name
=>
Doe
)
array(
id
=>
first_name
=>
Sally
last_name
=>
Smith
)
array(
id
=>
first_name
=>
Jane
last_name
=>
Jones
)
array(
id
=>
first_name
=>
Peter
last_name
=>
Doe
)
);
$firstNames = array_column($records
first_name
);
print_r($firstNames);
/*
Array
(
[
] => John
[
] => Sally
[
] => Jane
[
] => Peter
)
*/
$records = array(
array(
John
Doe
)
array(
Sally
Smith
)
array(
Jane
Jones
)
);
$lastNames = array_column($records
);
print_r($lastNames);
/*
Array
(
[
] => Doe
[
] => Smith
[
] => Jones
)
*/
$mismatchedColumns = array(
array(
a
=>
foo
b
=>
bar
e
=>
baz
)
array(
a
=>
qux
c
=>
quux
d
=>
corge
)
array(
a
=>
grault
b
=>
garply
e
=>
waldo
)
);
$foo = array_column($mismatchedColumns
a
b
);
print_r($foo);
/*
Array
(
[bar] => foo
[
] => qux
[garply] => grault
)
*/
array_column 用于获取二维数组中的元素(PHP >= )
复制代码 代码如下:
<?php
// Array representing a possible record set returned from a database
$records = array(
array(
id
=>
first_name
=>
John
last_name
=>
Doe
)
array(
id
=>
first_name
=>
Sally
last_name
=>
Smith
)
array(
id
=>
first_name
=>
Jane
last_name
=>
Jones
)
array(
id
=>
first_name
=>
Peter
last_name
=>
Doe
)
);
$first_names = array_column($records
first_name
);
print_r($first_names);
?>
Array
(
[
] => John
[
] => Sally
[
] => Jane
[
] => Peter
)<?php
// Using the $records array from Example #
$last_names = array_column($records
last_name
id
);
print_r($last_names);
?>
Array
(
[
] => Doe
[
] => Smith
[
] => Jones
[
] => Doe
)