array_sum()到数组中的值

时间:2016-06-29 08:56:53

标签: php

如何在我的循环中将array_sum添加到字符串中而不为其创建另一个foreach循环?我试图将所有数字组合在一起,而不是拥有这个多维数组然后只有值,我看到array_sum不会添加它们因为它在数组内部。任何想法?

{% with outer_counter = forloop.counter %}

我希望我的输出是

$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)

编辑:添加了$ proj_time的内容

1488 => 
    array (size=2)
      'item_value' => string 'Standby' (length=7)
      'hours' => string '40.00' (length=5)

2 个答案:

答案 0 :(得分:1)

而不是创建数组然后应用操作,而不是创建自己为什么不总结这样:

DEMO

xCal:description

<强>结果:

$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']; 
}

答案 1 :(得分:0)

试试这个

<?php
    $hours_arr = array();
    foreach($proj_time as $item){
        if(!isset($hours_arr [$item['project_id']]) || $hours_arr [$item['project_id']]['item_value'] != $item['item_value']) {     
            $hours_arr [$item['project_id']]['item_value'] = $item['item_value'];
            $hours_arr [$item['project_id']]['hours'][] = $item['hours'];
        } else {
            $hours_arr [$item['project_id']]['hours'][0] += $item['hours'];
        }
    }