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?

2
  • 3
    Possible duplicate of I want to add sub arrays to one single array in php Commented Sep 25, 2017 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. Commented Apr 8, 2021 at 2:52

5 Answers 5

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'));
Sign up to request clarification or add additional context in comments.

Comments

0

Use a loop and array_merge:

$filteredArray = array();
foreach ($all as $array) {
   $filteredArray = array_merge($filteredArray, $array['itens']);
}
print_r($filteredArray);

Comments

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

Comments

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

Comments

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',
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.