php计算特定数组内的总值而不是整个数组

时间:2013-02-05 00:50:50

标签: php arrays multidimensional-array calculated-field

我有一个看起来像的数组:

$costs = 
  Array
   (
    [0] => Array
       (
        [amount_set] => 27.99
        [amount_cost] => 17
        [amount_markup] => 3.6

    )

  )

  Array
      (
       [0] => Array
         (
        [amount_set] => 6.99
        [amount_cost] => 3.12
        [amount_markup] => 1          
       )

       [1] => Array
        (           
          [amount_set] => 16.99
          [amount_cost] => 10
          [amount_markup] => 2.54         
        )
)

我要做的是循环遍历$cost数组,并为每个数组计算amount_set的总值。

如果我使用:

foreach($costs as $cost) {
   $amount +=$cost['amount_set'];
}

然后我将获得所有组合amount_set值的总和,但我只想获得每个值的总和。例如,我的第一个总数将是27.99,第二个应该是23.98。我该怎么做呢?

1 个答案:

答案 0 :(得分:3)

如果我理解正确,$ cost是一组成本集,它是成本数组,你想要每个集合的总数。那意味着你需要这样的东西:

foreach($costs as $cost_set) {
    $amount = 0;
    foreach ($cost_set as $cost) {
        $amount += $cost['amount_set'];
    }
    $amounts[] = $amount;
}

这将根据成本组给出一系列小计。