I've found myself today really struggling with this subject and I'm pretty sure that there must be a better way to do this.
First of all my arrays have the same layout, I need to merge them and sum every value by domain.
Let me give you an example:
$array[0]['X1']['Y1'] = 1;
$array[0]['X1']['Y2'] = 2;
$array[0]['INFO']['DOMAIN'] = 'example1.com';
$array[1]['X1']['Y1'] = 1;
$array[1]['X1']['Y2'] = 2;
$array[1]['INFO']['DOMAIN'] = 'example1.com';
$array[2]['X1']['Y1'] = 2;
$array[2]['X1']['Y2'] = 5;
$array[2]['INFO']['DOMAIN'] = 'example2.com';
$array[3]['X1']['Y1'] = 2;
$array[3]['X1']['Y2'] = 5;
$array[3]['INFO']['DOMAIN'] = 'example2.com';
I need to produce the following new array:
$mergedArray[0]['X1']['Y1'] = 2;
$mergedArray[0]['X1']['Y2'] = 4;
$mergedArray[0]['INFO']['DOMAIN'] = 'example1.com';
$mergedArray[1]['X1']['Y1'] = 4;
$mergedArray[1]['X1']['Y2'] = 10;
$mergedArray[1]['INFO']['DOMAIN'] = 'example2.com';
I'm using the following code to achieve this (forgive me for the bad namings).
foreach($array as $subKey => $subValue) {
foreach($subValue as $key => $value) {
foreach($value as $key2 => $value2) {
if($key2=='DOMAIN' && !isset($merged[$value2])) {
$merged[$value2] = $subValue;
} else if ($key2=='DOMAIN' && isset($merged[$value2])) {
foreach($subValue as $key3=>$value3) {
foreach($value3 as $key4=>$value4) {
if($key4!='DOMAIN')
$merged[$value2][$key3][$key4] += $value4;
}
}
}
}
}
}
How could I improve this piece of code?
X1
,X2
,INFO
,DOMAIN
) ? Would the order of keys ever be different? \$\endgroup\$