0

I have this array in PHP.

$all = array(
array(
    'titulo' => 'Nome 1',
    'itens' => array( 'item1', 'item2', 'item3')
),
array(
    'titulo' => 'Nome 2',
    'itens' => array( 'item4', 'item5', 'item6')
),
array(
    'titulo' => 'Nome 4',
    'itens' => array( 'item7', 'item8', 'item9')
));

I need to merge specific child arrays. In other words, I need to get the itens column of data (which contains array-type data) as a flat result array like this:

$filteredArray = array('item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7', 'item8', 'item9');

I can do this using foreach(), but are there any other more elegant methods?

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Lincoln Lemos
  • 398
  • 2
  • 8
  • 3
    Possible duplicate of [I want to add sub arrays to one single array in php](https://stackoverflow.com/questions/14951811/i-want-to-add-sub-arrays-to-one-single-array-in-php) – ishegg Sep 25 '17 at 19:15
  • @ishegg that duplicate is not appropriate for this question because the OP doesn't want to flatten the entire contents of the input array, just one column of data. This is an important distinction. – mickmackusa Apr 08 '21 at 02:52

5 Answers5

3

You can reduce the itens column of your array, using array_merge as the callback.

$filteredArray = array_reduce(array_column($all, 'itens'), 'array_merge', []);

Or even better, eliminate the array_reduce by using the "splat" operator to unpack the column directly into array_merge.

$result = array_merge(...array_column($all, 'itens'));
Don't Panic
  • 41,125
  • 10
  • 61
  • 80
0

Use a loop and array_merge:

$filteredArray = array();
foreach ($all as $array) {
   $filteredArray = array_merge($filteredArray, $array['itens']);
}
print_r($filteredArray);
S.Gartmeier
  • 476
  • 5
  • 14
0

You can loop through your arrays and join them:

$filteredArray = array();

foreach($all as $items) {
    foreach($items["itens"] as $item) {
        array_push($filteredArray, $item);
    }
}
dvr
  • 885
  • 5
  • 20
0
function array_flatten($array) {
  if (!is_array($array)) {
    return false;
  }
  $result = array();
  foreach ($array as $key => $value) {
    if (is_array($value)) {
      $result = array_merge($result, array_flatten($value));
    } else {
      $result[$key] = $value;
    }
  }
  return $result;
}
Moeen Basra
  • 733
  • 4
  • 18
0

Another unmentioned technique is to iterate the input array and push a variable number of elements into the output array.

Code: (Demo)

$result = [];
foreach ($all as $row) {
    array_push($result, ...$row['itens']);
}
var_export($result);

Output:

array (
  0 => 'item1',
  1 => 'item2',
  2 => 'item3',
  3 => 'item4',
  4 => 'item5',
  5 => 'item6',
  6 => 'item7',
  7 => 'item8',
  8 => 'item9',
)
mickmackusa
  • 43,625
  • 12
  • 83
  • 136