简体   繁体   English

合并2个多维数组和总和值

[英]Merge 2 multi-dimension arrays and sum value

I have two multidimensional arrays which store x and y coordinates I am trying to merge together into a single array while preserving the x value but adding together the y values. 我有两个存储x和y坐标的多维数组,我试图将它们合并到一个数组中,同时保留x值,但将y值加在一起。

Array 1: 阵列1:

Array(
[0] => Array
    (
        [x] => 1327449600000
        [y] => 5
    )

[1] => Array
    (
        [x] => 1327450500000
        [y] => 1
    )

Array 2: 阵列2:

 Array(
[0] => Array
    (
        [x] => 1327449600000
        [y] => 1
    )

[1] => Array
    (
        [x] => 1327450500000
        [y] => 3
    )

So the combined outcome would be: 因此,合并结果将是:

 Array(
[0] => Array
    (
        [x] => 1327449600000
        [y] => 6
    )

[1] => Array
    (
        [x] => 1327450500000
        [y] => 4
    )

Any help would be greatly appreciated. 任何帮助将不胜感激。

Each of your original arrays is a vector; 每个原始数组都是一个向量。 let's allow them to contain an arbitrary amount of points (of any dimension): 让我们允许它们包含任意数量的点(任意维度):

function addPoints( vectorA, vectorB )
{
  if( vectorA.length != vectorB.length ) return [];
  var vectorC = [];
  for( var i=0; i<vectorA.length; ++i )
  {
    var tmp = [];
    for( var j in vectorA[i] ) tmp.push( vectorA[i][j]+vectorB[i][j] );
    vectorC.push( tmp );
  }
  return vectorC;
}

EDIT: 编辑:

I just realized you were writing PHP. 我刚刚意识到您正在编写PHP。 Give me a sec to convert the code please. 请给我几秒钟来转换代码。

function addPoints( $veca, $vecb )
{
   if( count($veca)!=count($vecb) ) return array();

   $vecc = array();
   for( $i=0; $i<count($veca); ++$i )
   {
      $tmp = array();
      foreach( $veca[$i] as $key => $val ) $tmp[$key] = $val + $vecb[$i][$key];
      $vecc[] = $tmp;
   }
   return $vecc;
}
function add_array($a1, $a2) {
    $c = count($a1);
    for ($i=0;$i<$c;$i++) {
        if (isset($a2[$i]) && isset($a2[$i]['y'])) {
            $a1[$i]['y'] += $a2[$i]['y'];
        }
    }
    return $a1;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM