0

I have an array which has multiple sets of data.

Is it possible to sum elements (not all) of the array. For example, is it possible to sum the first 5 sets of data in an array, then then next 7, then the next three etc.

EDIT:

I've tried the following but with not joy:

for ($p=0; $p<=8; $p++){
    $tot = 0;
    $resp = 0;

    $tot = $tot + $row4['Total_Staff'];
    $resp = $resp + $row4['Total_Resp'];

}

Clearly I am not using this correctly!

Array Output (print_r output):

Array ( [department] => Central>ACME>BusDev [Total_Staff] => 4 [Total_Resp] => 0 ) 
Array ( [department] => Central>ACME>ChemDev [Total_Staff] => 7 [Total_Resp] => 0 ) 
Array ( [department] => Central>ACME>Admin [Total_Staff] => 1 [Total_Resp] => 0 ) 
Array ( [department] => Central>ACME>Chemistry [Total_Staff] => 4 [Total_Resp] => 0 )
3
  • sure. with a correctly indexed for cycle. Commented Mar 11, 2014 at 13:59
  • Anything is possible. Can you show what you've done so far and ask a specific question for us to help with? Commented Mar 11, 2014 at 14:00
  • combination of array_sum() with array_slice() should do it.... perhaps you should show why your array makes it any more complicated Commented Mar 11, 2014 at 14:03

1 Answer 1

4

Use array_splice() to remove $numOfElems elements from the array and the return them. Use array_sum() to calculate the sum. Repeat the process until the array is empty.

$array = array(/* your array */)
$sets = array(5,7,3);
$sum_arr = array();

foreach ($sets as $numOfElems) {
    while (!empty($array)) {
        $elem_arr = array_splice($array, 0, $numOfElems);
        $sum[] = array_sum($elem_arr);
    }
}

print_r($sum_arr);

This will repeat the process with the same sets until it reaches the end of array. If you only want count($sets) number of iterations, then perhaps, you could change while to if.

Demo

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

8 Comments

Thanks Amal, seem to be having a problem - is this because my array has multiple sets of data (title, staff, responses)? Output from the above when I implement is lots of Array ().
Thanks for adding the demo - I think as I have three sets of data per array entry the above isn't working?
So, for the first three sets of data in the array I need to sum the staff part of the array and then `responses' part of the array etc.
@Homer_J: I have no idea how your array looks like. Add the output of echo '<pre>'.print_r($your_array_here, TRUE).'</pre>'; to the question.
there you go, thanks again for your assistance - struggling to get my head around this.
|

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.