使用PHP合并子数组

时间:2017-09-25 19:10:00

标签: php array-filter

我在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')
));

我如何才能获得上述结果?

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

我可以用foreach做到这一点,但是还有其他方法更干净吗?

5 个答案:

答案 0 :(得分:1)

您可以使用itens作为回调来缩小数组的array_merge列。

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

或者甚至更好,使用"splat" operator直接将列解压缩到array_reduce来消除array_merge

$result = array_merge(...array_column($all, 'itens'));

答案 1 :(得分:0)

使用循环和array_merge:

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

答案 2 :(得分:0)

您可以遍历数组并加入它们:

$filteredArray = array();

foreach($all as $items) {
    foreach($items["itens"] as $item) {
        array_push($filteredArray, $item);
    }
}

答案 3 :(得分: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;
}

答案 4 :(得分:0)

另一种未提及的技术是迭代输入数组并将可变数量的元素推送到输出数组中。

代码:(Demo)

INFO [SocketServer brokerId=0] Failed authentication with /10.240.0.35 (SSL handshake failed) (org.apache.kafka.common.network.Selector) [data-plane-kafka-network-thread-0-ListenerName(EXTERNAL-9094)-SSL-9]

INFO [SocketServer brokerId=0] Failed authentication with /10.240.0.159 (SSL handshake failed) (org.apache.kafka.common.network.Selector) [data-plane-kafka-network-thread-0-ListenerName(EXTERNAL-9094)-SSL-11]

INFO [SocketServer brokerId=0] Failed authentication with /10.240.0.4 (SSL handshake failed) (org.apache.kafka.common.network.Selector) [data-plane-kafka-network-thread-0-ListenerName(EXTERNAL-9094)-SSL-10]

INFO [SocketServer brokerId=0] Failed authentication with /10.240.0.128 (SSL handshake failed) (org.apache.kafka.common.network.Selector) [data-plane-kafka-network-thread-0-ListenerName(EXTERNAL-9094)-SSL-1]

输出:

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