SHARE
TWEET

Recursive arrayAddition() by Miro Balearski

MiroBalearski Mar 23rd, 2019 (edited) 62 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2.  
  3. $a = [
  4.     "ABC" => [
  5.         "A" => 1000,
  6.         "B" => 2000,
  7.         "C" => ['D'=> 3000,
  8.                 'E'=> 4000,
  9.                 'G'=> ['Z'=> 787878]
  10.                 ]
  11.             ]
  12.     ];
  13.  
  14. $b = [
  15.     "ABC" => [
  16.         "A" => 100,
  17.         "B" => 200,
  18.         "C" => ['D'=> 300,
  19.                 'E'=> 400,
  20.                 'F'=> 500,
  21.                 'G'=> ['R'=> 777777,
  22.                         'T'=> 888888,
  23.                         'Y'=> 999999,
  24.                        
  25.                        ]
  26.                ]
  27.     ]
  28. ];
  29.  
  30.  
  31. function arrayAddition($old, $new){
  32.  
  33.     foreach($new as $kk=>$vv){
  34.         if(is_array($vv)){
  35.             if(array_key_exists($kk, $old)){
  36.               $old[$kk]= arrayAddition($old[$kk], $new[$kk] );
  37.             }else{
  38.               $old[$kk]= $new[$kk];
  39.             }
  40.          
  41.         }else{
  42.             if(array_key_exists($kk, $old)){   
  43.                 $old[$kk]= ($new[$kk] + $old[$kk]);
  44.             }else{
  45.                 $old[$kk]= ($new[$kk]);
  46.             }
  47.         }
  48.     }
  49.  
  50.     return $old;   
  51. }
  52.  
  53.  
  54. $c = arrayAddition($a, $b);
  55.  
  56. print_r($a);
  57. print_r($b);
  58. print_r($c);
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top