与嵌套关联数组中相同键关联的值的总和


Sum of values associated to the same keys in nested associative array

我有如下所示的数组。我想要一个结果数组,其中对于具有相同值[tick_id]的所有行,对关键元素[tv][tu][cost][km]中的值求和。在这个例子中,我们应该求和数组元素0、1、2…的值[tv][tu][cost][km]。我该怎么做?

Array (
    [0] => stdClass Object (
        [id] => 15
        [user_id] => 44
        [name] => inspector1
        [tv] => 0.00
        [tc] => 0.00
        [tu] => 0.00
        [cost] => 0.00
        [kms] => 0
        [date_s] => 2012-03-30
        [notes] =>
        [tick_id] => 11
        [tot_fee] => 5500
    )
    [1] => stdClass Object (
        [id] => 39
        [user_id] => 46
        [name] => Assistant
        [tv] => 10.00
        [tc] => 0.00
        [tu] => 4.50
        [cost] => 0.00
        [kms] => 120
        [date_s] => 2012-03-31
        [notes] =>
        [tick_id] => 15
        [tot_fee] => 0
     )
    [2] => stdClass Object (
        [id] => 35
        [user_id] => 46
        [name] =>
        [tv] => 0.00
        [tc] => 0.00
        [tu] => 0.00
        [cost] => 0.00
        [kms] => 0
        [date_s] => 2012-03-30
        [notes] =>
        [tick_id] => 13
        [tot_fee] => 3200
    )
    …
)

很难判断代码的显示方式,但这应该是您所需要的:

// Create the cost total array
$cost = array();
// Iterate over each object in the given array
foreach ($array as $object)
{
  // If the tick_id has not yet been assigned as a key then do so with a default cost of 0
  if (!isset($cost[$object->tick_id]))
  {
    $cost[$object->tick_id] = 0;
  }
  // Increment the total cost for the given tick_id
  $cost[$object->tick_id] += $object->tv + $object->km + $object->tu + $object->cost;
}

$cost将是其中keytick_idvalue为总成本的阵列。