douhuan1901 2015-08-05 11:04
浏览 26

如何获得数组总和

I have 2 arrays.

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

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

How do I get the sum of the values on the $fruits array that are only available on the $purchased array? That is get the sum = 25

  • 写回答

2条回答 默认 最新

  • dpy83214 2015-08-05 11:06
    关注

    Try a loop -

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

报告相同问题?