Shafizadeh Shafizadeh - 6 months ago 8
PHP Question

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

I have a array like this:

$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
)
)
*/


Always there is 4 or less cases:


  • today

  • yesterday

  • in last week

  • in last month or more



And I'm trying to sum the
numb
item where
range
is
today
and there is another case in the
$results
array (or yesterday, or in last week, or in last month or more, or some of them, or all of them, doesn't matter .. Just there should be one more case except "today").

How can I do that?




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


Note: I wrote that
break
because the items are sorted in the array. I mean always
today
's items are either not exist or in the top of the array. So if that condition is
FALSE
then it also will be
FALSE
for the rest of items.

Answer

The other answers are missing a couple of keys he asked for in the question. He is looking to sum entries that are "today" if (and only if) there exist some entry in the array that isn't "today". While I agree the structure of the current array isn't ideal for this task, for the sake of simplicity, we will keep it and break it into a couple of steps

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

You were pretty close I feel like.

Note: This may not be the most elegant solution, but it's a simple and straight-forward solution that should be easy to follow.