合并和添加数组

时间:2019-05-02 13:30:32

标签: php arrays

我有两个数组: 1st:

[0] => 1, 
[1] => 2, 
[2] => 1, 
[3] => 2

第二:

Array ( 
    [0] => Array ( 
        [0] => 1 
        [1] => 2 
    ) 
    [1] => Array ( 
        [0] => 3 
        [1] => 4 
    ) 
    [2] => Array ( 
        [0] => 1 
        [1] => 2 
    ) 
    [3] => Array ( 
        [0] => 3 
        [1] => 4 
    ) 
)

所以我需要从第一个数组中选择值,并将它们插入第二个数组的键中,它应该像这样:

Array ( 
    [1] => Array ( 
        [0] => 1 
        [1] => 2 
    ) 
    [2] => Array ( 
        [0] => 3 
        [1] => 4 
    ) 
    [1] => Array ( 
        [0] => 1 
        [1] => 2 
    ) 
    [2] => Array ( 
        [0] => 3 
        [1] => 4 
    ) 
)

最后,我需要使最后一个数组看起来像这样:

Array ( 
    [1] => Array ( 
        [0] => 2 
        [1] => 4 
    ) 
    [2] => Array ( 
        [0] => 6 
        [1] => 8 
    )
)

您能帮我吗:我该怎么办?谢谢

1 个答案:

答案 0 :(得分:0)

所以基本上,如果我没记错的话,你想要的是相同索引值的总和。

$first = [1,2,1,2];
$second = [[1,2],[3,4],[1,2], [3,4]];

$final = [];

foreach($first as $key => $value)
{
  if(isset($final[$value]))
    {
      foreach($final[$value] as $k => $v)
            {
              $final[$value][$k] += $second[$key][$k];
            }
    }
  else
    {
      $final[$value] = $second[$key];
    }
}


echo "<pre>";
var_dump($final);