繁体   English   中英

如何求和特定数组项的值?

[英]How can I sum the values of specific array's item?

我有一个这样的数组:

$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

/*
Array
(
    [0] => Array
        (
            [numb] => 10
            [range] => today
        )

    [1] => Array
        (
            [numb] => 5
            [range] => today
        )

    [2] => Array
        (
            [numb] => 5
            [range] => yesterday
        )

    [3] => Array
        (
            [numb] => 15
            [range] => in last week
        )

    [4] => Array
        (
            [numb] => 10
            [range] => in last week
        )

    [5] => Array
        (
            [numb] => 5
            [range] => in last week
        )

    [6] => Array
        (
            [numb] => 15
            [range] => in last month or more
        )
)
*/

总是有 4 种或更少的情况:

  • 今天
  • 昨天
  • 在上周
  • 在上个月或更长时间

我正在尝试对rangetodaynumb项目求和,并且$results数组中还有另一种情况(或昨天,或上周,或上个月或更长时间,或其中一些,或全部,没关系.. 应该还有一个案例,除了“今天”)

我怎样才能做到这一点?


$score = null;
foreach($results as item) {
    if ( $item[range] == 'today' && /* another case exists */ ) {
        $score = item['numb'];
    } else {
        break;
    }
}

注意:我写了那个break是因为项目在数组中排序。 我的意思是总是today的项目要么不存在要么在数组的顶部。 因此,如果该条件为FALSE那么其余项目也将为FALSE

这应该这样做:

$score = 0;
foreach($results as $item) {
    if ( $item['range'] == 'today') {
        $score += item['numb'];
    }
}
var_dump($score); // The sum total of all the $result array's "numb" values

其他答案缺少他在问题中要求的几个键。 当(且仅当)数组中存在一些不是“今天”的条目时,他希望对“今天”的条目求和。 虽然我同意当前数组的结构对于此任务并不理想,但为了简单起见,我们将保留它并将其分解为几个步骤

//first lets scan the array to see if there is something that is not "today"
$allTodays = true;
foreach ($result as $row) {
   if($row['range'] !== 'today') {
    $allTodays = false;
    break;
  }
}
// now if there is something that is not today
// sum the todays
$score = null;
if (!$allTodays) {
  foreach ($results as $item) {
    if ($item['range'] == 'today') {
        $score += item['numb'];
    } else {
        break;
    }
  }
}

你离我很近,我觉得。

注意:这可能不是最优雅的解决方案,但它是一个简单而直接的解决方案,应该易于遵循。

您可以更改数组结构以求和:

<?php
$sums = array();
// init
foreach($results as $item) {
     if($item['range'] == 'today') { // if you only want today add this condition
         if (!array_key_exists($item['range'], $sums)) {
             $sums[$item['range']] = 0;
         }
         $sums[$item['range']] += $item['numb'];
     }
}

// $sums['in last week'] will contain 30

如果我理解正确的话,您的任务是一项非常常见的任务 - 您想首先对项目进行分组(基于“范围”字段),然后计算总和。

也许最简单的解决方案是将每个范围的结果存储在关联数组中:

$scores = [];

foreach ($results as $item) {
    if (! isset($scores[$item['range']])) {
        $scores[$item['range']] = $item['num'];
    } else {
        $scores[$item['range']] += $item['num'];
    }
}

print_r($scores);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM