PHP合并子数组

时间:2019-06-10 22:56:32

标签: php arrays

所以我有2个像这样的数组:

$a = array(array('1','2','3'), array('hello','darkness','my'));
$b = array(array('4','5','6'), array('old','friend','I'));

现在我想分别合并子数组:

$result = array(array_merge($a[0],$b[0]),array_merge($a[1],$b[1])));

结果:

#vardump($result)
array(2) {
  [0]=>
  array(6) {
    [0]=>
    string(1) "1"
    [1]=>
    string(1) "2"
    [2]=>
    string(1) "3"
    [3]=>
    string(1) "4"
    [4]=>
    string(1) "5"
    [5]=>
    string(1) "6"
  }
  [1]=>
  array(6) {
    [0]=>
    string(5) "hello"
    [1]=>
    string(8) "darkness"
    [2]=>
    string(2) "my"
    [3]=>
    string(3) "old"
    [4]=>
    string(6) "friend"
    [5]=>
    string(1) "I"
  }
}

这行得通...但是它看起来很笨拙,如果我需要合并可变数量的子数组,这不是一个好的解决方案。是否有用于此类操作的内置函数(或更简便的方法)?

2 个答案:

答案 0 :(得分:1)

我想出了以下内容(借助@panther的答案)

function subarray_merge(...$arrays){
    $result = array();
    foreach ($arrays as $k => $v) {
        if($k === 0) {
            $result = $v;
        }else{
            foreach ($v as $ks => $vs) {
                $result[$ks] = array_merge($result[$ks], $v[$ks]);
            }
        }
    }
    return $result;
}

print_r(subarray_merge($a,$b,$c));

答案 1 :(得分:0)

只需使用foreach循环。

<?php

$a = array(array('1','2','3'), array('hello','darkness','my'));
$b = array(array('4','5','6'), array('old','friend','I'));
$c = array(array('7','8','9'), array('old','friend','I'));

$defined_vars = get_defined_vars();

$result = [];

foreach ($defined_vars as $key => $arr) {
    if (in_array($key, ['_GET', '_POST', '_COOKIE', '_FILES', '_SESSION'])) continue;

    foreach ($arr as $k => $row) {
        if (!isset($result[$k])) {
            $result[$k] = $row;
        } else {
            foreach ($row as $r) {
                $result[$k][] = $r;
            }
        }
    }
}

echo '<pre>';
print_r($result);


--- result
Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
            [3] => 4
            [4] => 5
            [5] => 6
            [6] => 7
            [7] => 8
            [8] => 9
        )

    [1] => Array
        (
            [0] => hello
            [1] => darkness
            [2] => my
            [3] => old
            [4] => friend
            [5] => I
            [6] => old
            [7] => friend
            [8] => I
        )

)

此解决方案是“地狱”,但有效。正确的做法是使包装数组代替这些变量,例如

$array = [
    array(array('1','2','3'), array('hello','darkness','my')),
    array(array('4','5','6'), array('old','friend','I')),
    array(array('7','8','9'), array('old','friend','I'))
];

$result = [];

foreach ($array as $key => $arr) {
    foreach ($arr as $k => $row) {
        if (!isset($result[$k])) {
            $result[$k] = $row;
        } else {
            foreach ($row as $r) {
                $result[$k][] = $r;
            }
        }
    }
}

echo '<pre>';
print_r($result);