如何将特定数组项的值相加?

时间:2016-05-31 00:19:45

标签: php arrays

我有一个这样的数组:

$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个或更少的情况:

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

我试图将numb range today $results $score = null; foreach($results as item) { if ( $item[range] == 'today' && /* another case exists */ ) { $score = item['numb']; } else { break; } } break today中的另一个案例加上FALSE数组 ,或者在上周,或者在上个月或者更长时间,或者其中一些,或者所有这些,都不重要......除了"今天")之外还应该再增加一个案例。 EM>

我该怎么做?

FALSE

注意:我写了private void InitializeComponent() { // Your form properties here this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Form1_KeyDown); } 因为项目在数组中排序。我的意思是总是private void Form1_KeyDown(object sender, KeyEventArgs e) { // To know if your event is working and the value of the key who's pressed MessageBox.Show("Key Pressed = " + e.KeyCode.ToString() + ", Value = " + e.KeyValue.ToString()); // Example - add some actions bellow if (e.KeyValue == 13) MessageBox.Show("Return Key Pressed"); } 的项目不存在或者在数组的顶部。因此,如果该条件为foo,则其余项目也为this

4 个答案:

答案 0 :(得分:0)

应该这样做:

$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

答案 1 :(得分:-1)

其他答案缺少他在问题中要求的几把钥匙。如果(并且仅当)数组中存在一些不是“今天”的条目,他正在寻找对“今天”的条目求和。虽然我同意当前阵列的结构不适合这项任务,但为了简单起见,我们将保留它并将其分解为几个步骤

//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;
    }
  }
}

我感觉非常接近。

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

答案 2 :(得分:-2)

你可以改变数组结构以求和:

<?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

答案 3 :(得分:-3)

如果我理解正确,你的任务很常见 - 你想先将项目分组(基于'范围'字段),然后计算总和。

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

$scores = [];

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

print_r($scores);