0

I have the following:

Array 
( 
    [0] => Array 
    ( 
        [department] => Central>ACME>BusDev 
        [Total_Staff] => 4 
        [Total_Resp] => 0 
    ) 
)

There are over 150 of these within the array.

I can easily sum, for example, Total_Staff and Total_Resp using something like:

foreach($arr as $num => $values) {
    $sum_staff += $values[ 'Total_Staff' ];
    $sum_resp += $values[ 'Total_Resp' ];
}

However what I need to do is sum only elements of the array, for example I need to sum Total_Staff and Total_resp that lies between indexes 0 and 7 or 12 and 58.

Not sure how to go about this.

3 Answers 3

1

Is this what you need

foreach($arr as $num => $values) {
    if(($num >= 0 && $num <= 7) || ($num >= 12 && $num <= 58))
        $sum += $values[ 'Total_Staff' ];
}
Sign up to request clarification or add additional context in comments.

Comments

0

Using a for loop would be the way to solve this:

 $start = 12;
 $end = 58;
 $sum_total_staff = 0;
 $sum_total_resp = 0;

 for( $i = $start; $i <= $end; $i++ ) {       
     $sum_total_staff += $arr[$i]["Total_Staff"];   
     $sum_total_resp += $arr[$i]["Total_Resp"];   
 }

Comments

0

Id say use these 2 function to slice & merge the arrays. It will get 8 arrays from which are between indexes 0-7 (with 0 and 7 included) and same with the second one. If you want without 0 and 7, it would be with arguments 1, 6, so array_slide($arr, 1, 6); and so on.

$new_arr1 = array_slice($arr, 0, 8);
$new_arr2 = array_slice($arr, 12, 47);
$arr = array_merge($new_arr1, $new_arr2);

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.