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.

2

3 Answers 3

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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

1 Comment

thanks for your sharing, i will also try out this set of code.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.