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.
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;
}
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;
}