使用PHP合并子数组

使用PHP合并子数组

问题描述:

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?

我在PHP中有这个数组。 p>

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

我如何获得 上面这个结果? p>

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

我可以使用foreach执行此操作,但是还有其他方法更干净吗? p> DIV>

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