Sizzling Code Sizzling Code - 7 months ago 13
PHP Question

merge multi dimentional php array with in

this kinda question might have been asked many times, but mine is little difference in a sense that i dont have any other array to merge with.

i want to merge arrays with in multidimentional array.

So that its not a multi dimentional any more.

Here is the array i have got.

Array
(
[2013-12-01::2015-07-29] => Array
(
[TotalMonths] => 1
[0] => 2015-07-01
)

[2015-11-01::2016-03-30] => Array
(
[TotalMonths] => 5
[0] => 2015-11-01
[1] => 2015-12-01
[2] => 2016-01-01
[3] => 2016-02-01
[4] => 2016-03-01
)

[2016-04-01::2017-11-30] => Array
(
[TotalMonths] => 3
[0] => 2016-04-01
[1] => 2016-05-01
[2] => 2016-06-01
)

)


what i am trying is merging all arrays with in. But the index (TotalMonths) is common so only for that it should sum values like
(1+5+3) = 8

which will be reflected in new merged array.

I have tried this example also..
PHP: Turning multidimensional arrays to single dimension arrays

but not sure how i am getting same values..

This is what i have tried so far..

print_r($collidingMonths);
$outPutArray = array();
foreach($collidingMonths as $innerArray) {
$outPutArray[key($innerArray)] = current($innerArray);
}

print_r($outPutArray);


But sadly i am getting the result which i dont want :(

Array
(
[TotalMonths] => 3
)

Answer

The most straight-forward way would be to take the TotalMonths value out of the array elements before merging:

$result = [];
$totalMonths = 0;
foreach($collidingMonths as $innerArray) {
    $TotalMonths += $innerArray['TotalMonths'];
    unset($innerArray['TotalMonths']);
    $result = array_merge($result, $innerArray);
}