dialogik
dialogik

Reputation: 9552

Get flat array of values from a specified column of a 2d array

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]"
}

Upvotes: 9

Views: 9884

Answers (2)

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]
)

Upvotes: 2

moonwave99
moonwave99

Reputation: 22810

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);

Upvotes: 21

Related Questions