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')
));
How i can get this result above?
$filteredArray = array( 'item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7', 'item8', 'item9');
I can do this with foreach, but have any other method more clean?
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'));
Use a loop and array_merge:
$filteredArray = array();
foreach ($all as $array) {
$filteredArray = array_merge($filteredArray, $array['itens']);
}
print_r($filteredArray);
You can loop through your arrays and join them:
$filteredArray = array();
foreach($all as $items) {
foreach($items["itens"] as $item) {
array_push($filteredArray, $item);
}
}
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;
}