Search code examples
phparraysforeachsubstrsubtraction

Subtract two arrays in PHP using Raspberry


I have two arrays that each contains one mysql select from different days (24h interval). Arrays contains 1440 entries with another sub-array(temp1, temp2, temp3 and date). I tried foreach($array as $key=>$val) but I can't subtract $val with or from another, let's say, $val2. The most legit way to do this is (based on web search):

foreach($yesterdayValues as $key=>$val){
    if(substr($key, 0, 5) == 'temp2')
        $todayValues[$key] -= $val;  
}

But it does not work.

The main idea is to subtract temp2 values from today with the same temp2 values from yesterday in order to see changes in temperature. And display them nicely.


Solution

  • The answer is this (but it's kind of static for the moment):

    for($i=0;$i<1440;$i++){
        (float)$yesterdayValues[$i]['temp2'] = (float)$last24hourValues[$i]['temp2'] - (float)$yesterdayValues[$i]['temp2'];
    }
    

    There are 1440 entries in 24h, and the key cand be acessed manually in a simple for. Maybe this can work with foreach instead of simple for. I will check later.