2

I have 2 arrays as below:

array(2) { ["2018-05"]=> string(2) "15" ["2018-06"]=> string(3) "100" }
array(1) { ["2018-05"]=> string(1) "5" } 

I wish to do calculation to find the difference so it will return:

array(2) { ["2018-05"]=> string(2) "10" ["2018-06"]=> string(3) "100" }

As this is a multidimensional array, I'm not sure how to show the "year-month" as the array key, can someone please enlighten me?

Thanks.

Yen
  • 45
  • 6
  • You can get the keys using [array_keys](http://php.net/manual/en/function.array-keys.php), so you need to get both key list merge them and do the math – ka_lin May 22 '18 at 13:42
  • may be help https://stackoverflow.com/questions/1496682/sum-array-values-of-the-same-key – daremachine May 22 '18 at 13:46

3 Answers3

1

Try this code

$a = ["2018-05"=> "15", "2018-06"=> "100" ];
$b = ["2018-05"=> "5"];

$c = $a;

foreach($b as $k=> $i){
    if(array_key_exists($k,$c)){
        $c[$k] = $a[$k] - $b[$k];
    }
    else{
        $c[$k] = 0-$i;
    }
}
Davit Huroyan
  • 302
  • 4
  • 16
0

Assuming that you don't want to take into account same values and you want absolute values, this should work

$els[]["2018-05"]="15";
$els[]["2018-06"]="100";
$els[]["2018-05"]="5" ;
$els[]["2018-05"]="1" ;//added
$els[]["2018-06"]="50";//added

    $newEls = [];

    foreach($els as $key => $el){

        $newEls[key($el)] = $el[key($el)];

          foreach($els as $key2 => $el2){

              if(key($els[$key]) == key($els[$key2]) && $els[$key][key($els[$key])] != $els[$key2][key($els[$key2])]){

              $newEls[key($el)] = abs($els[$key][key($els[$key])] - $els[$key2][key($els[$key2])]);

              }


        }


        }

    echo "<pre>";print_r($newEls);

If you want to keep same values like [0]["2018-05"]="15" and [1]["2018-05"]="15" it's necessary another approach. Because maybe the best approach is to use queues.

Emeeus
  • 5,072
  • 2
  • 25
  • 37
0
<?php

$a = ['2018-05'=> '15', '2018-06'=> '100'];
$b = ['2018-05'=> '5'];

$years = array_map(NULL, $a, $b);
$years = array_combine(array_keys($a), $years);

$differences = array_map(function ($year_diffs) : float {

    // Did we get a pair to compare?
    $has_diff = isset($year_diffs[0]) and isset($year_diffs[1]);

    // If we got a pair then compare, else assume we got one.
    $diff = $has_diff ? abs($year_diffs[0] - $year_diffs[1]) : $year_diffs[0];

    return $diff;
}, $years);

var_dump($differences);

https://3v4l.org/BSEui

I've had to assume a few things

  • $a will always contain the dominate key
  • Both arrays contain the same keys as each other without gaps
  • There will always be one or two difference numbers

I feel like whatever your real system is, probably violates the above criteria but you'd need to provide more context for a different solution

arcanine
  • 1,933
  • 1
  • 15
  • 22