Suzed Suzed - 5 months ago 11
PHP Question

array_sum() to values within an array

How can i add array_sum to the string in my loop without making another foreach loop for it? I am trying to combine all of the numbers together instead of having this multi dimensional array and then just have the value and i see that array_sum wont add them up because its inside of an array. any ideas?

$hours_arr = array();
foreach($proj_time as $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 would like my output to 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
)

)

Answer

Instead of creating array and then applying operation, while creating itself why don't you sum up like this:

DEMO

$hours_arr = array();
foreach($proj_time as $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
        )

)