I have an array that contains 4 arrays with one value each.
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]"
}
}
What is the best (=shortest, native PHP functions preferred) way to flatten the array so that it just contains the email addresses as values:
array(4) {
[0]=>
string(19) "[email protected]"
[1]=>
string(19) "[email protected]"
[2]=>
string(19) "[email protected]"
[3]=>
string(19) "[email protected]"
}
Arrays ¶ An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more.
In PHP, there are three types of arrays: Indexed arrays - Arrays with a numeric index. Associative arrays - Arrays with named keys. Multidimensional arrays - Arrays containing one or more arrays.
In PHP 5.5 you have array_column
:
$plucked = array_column($yourArray, 'email');
Otherwise, go with array_map
:
$plucked = array_map(function($item){ return $item['email'];}, $yourArray);
You can use a RecursiveArrayIterator
. This can flatten up even multi-nested arrays.
<?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]
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With