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.
    – STT LCU
    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?
    – jterry
    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
    – Mark Baker
    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

8
  • 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 ().
    – Homer_J
    Mar 11, 2014 at 14:14
  • Thanks for adding the demo - I think as I have three sets of data per array entry the above isn't working?
    – Homer_J
    Mar 11, 2014 at 14:15
  • 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
    Mar 11, 2014 at 14:16
  • @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. Mar 11, 2014 at 14:19
  • there you go, thanks again for your assistance - struggling to get my head around this.
    – Homer_J
    Mar 11, 2014 at 14:29

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.