简体   繁体   English

从另一个不相等的数组中减去数组值

[英]subtracting array values from another unequal array

I have the following which works just fine when the arrays are of an equal length: 当数组的长度相等时,我可以使用以下命令:

(example) (例)

$highNums = array(10,20,30,40,50,60);
$lowNums = array(0,1,2,3,4,5);

$result = array();
for($i=0;$i<count($highNums);$i++)
{
    $result[$i] = $highNums[$i]-$lowNums[$i];
}

The problem lies in that the array keys are dates (months) pulled from the database and where there is, say, 'january' and a value in the $lowNums array there won't always be a 'january' record in the $highNums. 问题在于,数组键是从数据库中提取的日期(月),并且在其中存在“ january”和$ lowNums数组中的值的情况下,$ highNums中不会总是存在“ january”记录。

Is there any way to detect any missing values in each array and fill them with 0? 有什么方法可以检测每个数组中的任何缺失值并将其填充为0? } }

foreach ($highNums as $key=>$val) {

     if(array_key_exists($key, $lowNums)){
           $result[$key] = $highNums[$key]-$lowNums[$key];
     }else{
           $result[$key]=0;
     }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM