计算对象中的和

时间:2012-06-12 12:50:43

标签: php object

我需要做这件事: 我有一个像下面的对象,但我需要做对象数量的总和,如object1_(任何),object2_(任何)

stdClass Object
(
    [object1_2012_06_12] => 16
    [object2_2012_06_12] => 10
    [object1_2012_06_11] => 16
    [object2_2012_06_11] => 10
)

例如: object1 _(任何的总和将是(object1_2012_06_12 + object1_2012_06_11)=(16 + 16)= 32

3 个答案:

答案 0 :(得分:7)

您可以将对象转换为数组:

$sum = 0;
foreach ((array)$myobj as $v) {
  $sum += intval($v);
}

或者按照@MarkBaker的建议:

$sum = array_sum((array)$myobj);

答案 1 :(得分:0)

在使用strtok

的第一个下划线之前,只需浏览对象属性和基于部分的求和
$sums = array();
foreach ($my_object as $key => $value) {
    $key = strtok($key, '_');

    if (!isset($sums[$key])) {
            $sums[$key] = $value;
    } else {
            $sums[$key] += $value;
    }
}

print_r($sums);

或者:

function sum_of_object_starting_with($my_object, $starts_with)
{
    $sum = 0; $prefix_len = strlen($starts_with);
    foreach ($my_object as $key => $value) {
        if (strncmp($key, $starts_with, $prefix_len)) {
            $sum += $value;
        }
    }
    return $sum;
}

print_r(sum_of_object_starting_with($my_object, 'object1_'));

答案 2 :(得分:0)

此代码将获得您想要的值:

function sum_by_object_name ($data, $objName) {

  // Temporary array to hold values for a object name
  $objValues = array();

  // Convert input object to array and iterate over it
  foreach ((array) $data as $key => $val) {

    // Extract the object name portion of the key
    $keyName = implode('_', array_slice(explode('_', $key), 0, -3));

    // If object name is correct push this value onto the temp array
    if ($keyName == $objName) {
      $objValues[] = $val;
    }

  }

  // Return the sum of the temp array
  return array_sum($objValues);

}

// Calculate the total of $object
$total = sum_by_object_name($object, 'object1');

See it working