coder1
coder1

Reputation: 65

Check if array value changed or not into foreach loop php?

We have a array like this:

Array(
[0]=>Array([HospitalName]=>'h1' [count]=>23)
[1]=>Array([HospitalName]=>'h1' [count]=>25)
[2]=>Array([HospitalName]=>'h1' [count]=>40)
[3]=>Array([HospitalName]=>'h1' [count]=>50)
[4]=>Array([HospitalName]=>'h1' [count]=>23)
[5]=>Array([HospitalName]=>'h2' [count]=>44)
[6]=>Array([HospitalName]=>'h2' [count]=>52)
[7]=>Array([HospitalName]=>'h2' [count]=>49)

)

I want to calculate h1 and h2 sum of count values.

sum of => h1[count]=>161
sum of => h2[count]=>145

How can I do with PHP?

Upvotes: 1

Views: 880

Answers (2)

Justinas
Justinas

Reputation: 43479

Use foreach loop for that:

 $sums = [];

 foreach ($myArray as $values) {
    if (isset($sums[$values['HospitalName']])) {
        $sums[$values['HospitalName']] += $values['count'];
    } else {
        $sums[$values['HospitalName']] = $values['count'];
    }
 }

Upvotes: 1

Kevin
Kevin

Reputation: 41885

You can use another container which will hold the sum of those values from that array:

$sum = array();
foreach($array as $values) {
    // simple initialization
    if(!isset($sum[$values['HospitalName']])) {
        $sum[$values['HospitalName']] = 0;
    }
    $sum[$values['HospitalName']] += $values['count'];
}

Basically, you just use the HospitalName as your key, then every time the corresponding key matches in the loop, it will just sum it to its designated hospital name.

Here's what $sum would look like

Upvotes: 1

Related Questions