php - array_sum() to values within an array -
how can add array_sum string in loop without making foreach loop it? trying combine of numbers instead of having multi dimensional array , have value , see array_sum wont add them because inside of array. ideas?
$hours_arr = array(); foreach($proj_time $item){ $hours_arr [$item['project_id']]['item_value'] = $item['item_value']; $hours_arr [$item['project_id']]['hours'][] = $item['hours']; } //output array (size=3) 4 => array (size=2) 'item_value' => string 'coaching' (length=8) 'hours' => array (size=1) 0 => string '999.99' (length=6) 1487 => array (size=2) 'item_value' => string 'standby' (length=7) 'hours' => array (size=1) 0 => string '15.00' (length=5) 1488 => array (size=2) 'item_value' => string 'standby' (length=7) 'hours' => array (size=4) 0 => string '10.00' (length=5) 1 => string '10.00' (length=5) 2 => string '10.00' (length=5) 3 => string '10.00' (length=5)
i output be
1488 => array (size=2) 'item_value' => string 'standby' (length=7) 'hours' => string '40.00' (length=5)
edit: added contents of $proj_time
array ( [0] => array ( [project_id] => 4 [consultant_id] => 51 [engagement_id] => 8 [hours] => 999.99 [item_value] => coaching ) [1] => array ( [project_id] => 1487 [consultant_id] => 1 [engagement_id] => 1 [hours] => 15.00 [item_value] => standby ) [2] => array ( [project_id] => 1488 [consultant_id] => 31 [engagement_id] => 7 [hours] => 10.00 [item_value] => design app rfp ) [3] => array ( [project_id] => 1488 [consultant_id] => 32 [engagement_id] => 41 [hours] => 10.00 [item_value] => training ) [4] => array ( [project_id] => 1488 [consultant_id] => 55 [engagement_id] => 41 [hours] => 10.00 [item_value] => training ) [5] => array ( [project_id] => 1488 [consultant_id] => 1 [engagement_id] => 1 [hours] => 10.00 [item_value] => standby ) )
instead of creating array , applying operation, while creating why don't sum this:
$hours_arr = array(); foreach($proj_time $item){ $hours_arr [$item['project_id']]['item_value'] = $item['item_value']; if(array_key_exists('hours', $hours_arr [$item['project_id']])) $hours_arr [$item['project_id']]['hours'] += $item['hours']; else $hours_arr [$item['project_id']]['hours'] = $item['hours']; }
result:
array ( [4] => array ( [item_value] => coaching [hours] => 999.99 ) [1487] => array ( [item_value] => standby [hours] => 15 ) [1488] => array ( [item_value] => standby [hours] => 40 ) )
Comments
Post a Comment