Skip to content
Advertisement

How to add arrays with the same months in a loop?

Array Months

array(8) { [0]=> string(2) "05" [1]=> string(2) "09" [2]=> string(2) "08" [3]=> string(2) "07" [4]=> string(2) "05" [5]=> string(2) "07" [6]=> string(2) "06" [7]=> string(2) "07" }


string(41) "["05","09","08","07","05","07","06","07"]"

Array Values of Months

array(8) { [0]=> string(5) "20000" [1]=> string(5) "10000" [2]=> string(5) "10000" [3]=> string(5) "15000" [4]=> string(5) "10000" [5]=> string(5) "50000" [6]=> string(5) "10000" [7]=> string(5) "14000" }

string(65) "["20000","10000","10000","15000","10000","50000","10000","14000"]"

So, I wanted to add the number that falls in the same month

05 => 20000
05 => 10000
06 => 10000
07 => 15000
07 => 50000
07 => 14000
08 => 10000
09 => 10000

Desired Output

string(106) "{"1":0,"2":0,"3":0,"4":0,"5":"30000","6":"10000","7":"79000","8":"10000","9":"10000","10":0,"11":0,"12":0}"

Code:

$mainarr = [];

foreach ($loans3rdChart as $key => $value) {

      for ($i=1; $i <=12 ; $i++) {

      if(!empty($mainarr[$i])){

        //$mainarr[$i]+=$value['y'];

      }else{

        if($i==$value['month_release']){

          $mainarr[$i] = $value['amount_granted'];

        }else{

          $mainarr[$i] = 0;

        }

      }

    }//end loop

  }

Output:

string(106) "{"1":0,"2":0,"3":0,"4":0,"5":"20000","6":"10000","7":"15000","8":"10000","9":"10000","10":0,"11":0,"12":0}"

Please help me figure this out. Thank you.

Advertisement

Answer

Your problem is that you are not considering that on the 2nd time you arrive at a month that already exists you need to add it to the existing value … here is an example to get you through with all:

<?php
$months = ["05","09","08","07","05","07","06","07"];
$values = ["20000","10000","10000","15000","10000","50000","10000","14000"];
foreach($months as $key => $month){
    if(!isset($newArray[$month])){
        $newArray[$month] = $values[$key];
    } else {
        $newArray[$month] = $newArray[$month] + $values[$key];
    }
}
for ($i=1; $i <=12 ; $i++) {
    if(strlen($i) == 1){
        $id = "0$i";
    } else {
        $id = $i;
    }
    if(!isset($newArray[$id])){
        $newArray[$id] = 0;
    }
}
ksort($newArray);
print_r(json_encode($newArray));

Will return:

{"01":0,"02":0,"03":0,"04":0,"05":30000,"06":"10000","07":79000,"08":"10000","09":"10000","10":0,"11":0,"12":0}

Edit — I have edited my code and added the 0 for the numbers to be 2 figures for each month.

Just want to emphasize there are plenty more ways to do this! 🙂

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement