Merge 2 multi-dimension arrays and sum value

2019-02-28 09:49发布

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.

Array 1:

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

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

Array 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.

2条回答
Explosion°爆炸
2楼-- · 2019-02-28 10:16
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;
}
查看更多
混吃等死
3楼-- · 2019-02-28 10:17

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. 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;
}
查看更多
登录 后发表回答