Search code examples
phparraysmultidimensional-arrayflattenarray-column

Create a flat array of values from an array column containing array-type data


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?


Solution

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