我有一个数组,其中包含 4 个数组,每个数组都有一个值。
array(4) {
[0]=>
array(1) {
["email"]=>
string(19) "[email protected]"
}
[1]=>
array(1) {
["email"]=>
string(19) "[email protected]"
}
[2]=>
array(1) {
["email"]=>
string(19) "[email protected]"
}
[3]=>
array(1) {
["email"]=>
string(19) "[email protected]"
}
}
扁平化数组使其仅包含电子邮件地址作为值的最佳(=最短、首选原生 PHP 函数)方法是什么:
array(4) {
[0]=>
string(19) "[email protected]"
[1]=>
string(19) "[email protected]"
[2]=>
string(19) "[email protected]"
[3]=>
string(19) "[email protected]"
}
array_column
:
$plucked = array_column($yourArray, 'email');
array_map
:
$plucked = array_map(function($item){ return $item['email'];}, $yourArray);
RecursiveArrayIterator
。这甚至可以展平多重嵌套数组。
<?php
$arr1=array(0=> array("email"=>"[email protected]"),1=>array("email"=>"[email protected]"),2=> array("email"=>"[email protected]"),
3=>array("email"=>"[email protected]"));
echo "<pre>";
$iter = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr1));
$new_arr = array();
foreach($iter as $v) {
$new_arr[]=$v;
}
print_r($new_arr);
OUTPUT:
Array
(
[0] => [email protected]
[1] => [email protected]
[2] => [email protected]
[3] => [email protected]
)