在PHP中合并数组[新]

时间:2019-03-21 03:09:43

标签: php arrays

我有三个数组:

$a = (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10);
$b = (b1, b2, b3, b4, b5, b6, b7, b8, b9, b10);
$c = (c1, c2, c3, c4, c5, c6, c7, c8, c9, c10);

我想结合这些数组来创建:

$new1 = (a1, a2, b1, b2, c1, c2);

$new2 = (a3, a4, b3, b4, c3, c4);

$new3 = (a5, a6, b5, b6, c5, c6);

$new4 = (a7, a8, b7, b8, c7, c8);

$new5 = (a9, a10, b9, b10, c9, c10);

如何做到这一点?

2 个答案:

答案 0 :(得分:1)

您,您想使用array_maparray_chunk将每个数组映射到其分块版本中,以便将它们分成2个元素数组。然后,您需要减少它们,以便每个块都进入相同的最终数组中,为此您将使用array_reduce

$a = array('a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'a10');
$b = array('b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8', 'b9', 'b10');
$c = array('c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9', 'c10');

$final = array_reduce(array_map(function($el) {
             return array_chunk($el, 2);
         }, [$a, $b, $c]), function($carry, $item) {
             foreach($item as $key => $value) {
                 if (!isset($carry[$key])) {
                     $carry[$key] = [];
                 }
                 $carry[$key] = array_merge($carry[$key], $value);
             }
             return $carry;
         });

$new1 = $f[0];
$new2 = $f[1];
$new3 = $f[2];
$new4 = $f[3];
$new5 = $f[4];

var_dump($f);
/*
 array(5) {
  [0]=>
  array(6) {
    [0]=>
    string(2) "a1"
    [1]=>
    string(2) "a2"
    [2]=>
    string(2) "b1"
    [3]=>
    string(2) "b2"
    [4]=>
    string(2) "c1"
    [5]=>
    string(2) "c2"
  }
  [1]=>
  array(6) {
    [0]=>
    string(2) "a3"
    [1]=>
    string(2) "a4"
    [2]=>
    string(2) "b3"
    [3]=>
    string(2) "b4"
    [4]=>
    string(2) "c3"
    [5]=>
    string(2) "c4"
  }
  [2]=>
  array(6) {
    [0]=>
    string(2) "a5"
    [1]=>
    string(2) "a6"
    [2]=>
    string(2) "b5"
    [3]=>
    string(2) "b6"
    [4]=>
    string(2) "c5"
    [5]=>
    string(2) "c6"
  }
  [3]=>
  array(6) {
    [0]=>
    string(2) "a7"
    [1]=>
    string(2) "a8"
    [2]=>
    string(2) "b7"
    [3]=>
    string(2) "b8"
    [4]=>
    string(2) "c7"
    [5]=>
    string(2) "c8"
  }
  [4]=>
  array(6) {
    [0]=>
    string(2) "a9"
    [1]=>
    string(3) "a10"
    [2]=>
    string(2) "b9"
    [3]=>
    string(3) "b10"
    [4]=>
    string(2) "c9"
    [5]=>
    string(3) "c10"
  }
}

答案 1 :(得分:0)

您需要将所有数组添加到一个数组中

  1. 然后应用计数为$a/2的while循环
  2. 然后使用array_map返回带有迭代索引值加1的返回值。这意味着,如果0分别是其获取a1,a2值。
  3. 然后最终合并数组并与结果数组一起传递

Sandbox Test

$a = Array('a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'a10');
$b = Array('b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8', 'b9', 'b10');
$c = Array('c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9', 'c10');
$arr = [$a,$b,$c];
$i=0;
$res=[];
while($i < (count($a)/2)){
    $res[$i]=call_user_func_array('array_merge',array_map(function($ar=[]) use ($i){
       return [$ar[$i],$ar[$i+1]];
    },$arr));
    $i++;
}
print_r($res);
print_r($res[0]);
$new1=$res[0];
$new2=$res[1];
$new3=$res[2];

print_r($new1);
print_r($new2);
print_r($new3);