如何获得数组总和

时间:2015-08-05 11:04:33

标签: php arrays sum filtering

我有2个阵列。

$fruits = [
    'mango' => 20,
    'apple' => 30,
    'orange' => 10,
    'banana' => 5,
];

$purchased = ['mango','banana'];

如何获取$fruits数组上仅在$purchased数组上可用的值的总和?得到总和= 25

2 个答案:

答案 0 :(得分:4)

尝试循环 -

$sum = 0;
foreach($purchased as $v) {
   $sum += (!empty($fruits[$v]) ? $fruits[$v] : 0); 
}

答案 1 :(得分:1)

  1. 过滤SELECT grades_eng.Grade, domain_math_eng.Domain, cluster_eng.Cluster, math_standards_eng.Standard FROM math_standards_eng INNER JOIN grades_eng ON math_standards_eng.Grade_Id = grades_eng.Id INNER JOIN domain_math_eng ON math_standards_eng.Domain_Math_Eng_Id = domain_math_eng.Id INNER JOIN cluster_eng ON math_standards_eng.Cluster_Eng_Id = cluster_eng.Id 数组以仅保留所购买的密钥。
  2. 汇总剩下的所有值。
  3. 以下是基于函数的方法,它会翻转$fruits元素的键和值,然后过滤$purchased,然后对剩余值求和。

    代码:(Demo

    $fruits

    输出:

    $fruits = [
        'mango' => 20,
        'apple' => 30,
        'orange' => 10,
        'banana' => 5,
    ];
    
    $purchased = ['mango','banana'];
    echo array_sum(array_intersect_key($fruits,array_flip($purchased))),"\n";
    
    $purchased = ['mango','banana','orange','apple'];
    echo array_sum(array_intersect_key($fruits,array_flip($purchased))),"\n";
    
    $purchased = [];
    echo array_sum(array_intersect_key($fruits,array_flip($purchased)));
    

    *注意,这不会像循环一样快,但它确实允许单行操作,并且不需要声明 tally 变量。