1

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?

1
  • Welcome to Stack Overflow. Please take a few minutes and read stackoverflow.com/help/how-to-ask. In your specific case, what did you try so far? Please provide some sample code. Commented Dec 10, 2014 at 14:21

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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'];
    }
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.