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

时间:2012-04-04 07:40:54

标签: php arrays

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

[km]

1 个答案:

答案 0 :(得分:1)

很难说你的代码显示的方式,但这应该是你需要的:

// 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为总费用。