2

我需要做这件事:我有一个像下面这样的对象,但我需要做对象1_(anything),object2_(anything)等对象数量的总和

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

例如:object1_( anything )的总和将是 (object1_2012_06_12 + object1_2012_06_11) = (16+16)=32

4

3 回答 3

8

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

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

或者按照@MarkBaker 的建议:

$sum = array_sum((array)$myobj);
于 2012-06-12T12:52:33.480 回答
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');

看到它工作

于 2012-06-12T13:12:21.927 回答
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_'));
于 2012-06-12T13:05:27.907 回答