1

我为此尝试了大约 20 种不同的想法,我想我已经走了很多圈,我不记得我从哪里开始了。我相信这也是一个简单的。

我有一个数组;

Array
(
    [0] => Array
        (
            [employee] => 15
            [first_name] => Person1
            [surname] => Person1
            [totaltime] => 183.75
            [type] => 0

        )

    [1] => Array
        (
            [employee] => 15
            [first_name] => Person1
            [surname] => Person1
            [totaltime] => 64.50
            [type] => 1            
        )

    [2] => Array
        (
            [employee] => 23
            [first_name] => Person2
            [surname] => Person2
            [totaltime] => 2.00
            [type] => 0
        )

    [3] => Array
        (
            [employee] => 51
            [first_name] => Person3 
            [surname] => Person3
            [totaltime] => 119.25
            [type] => 0            
        )

    [4] => Array
        (
            [employee] => 59
            [first_name] => Person4
            [surname] => Person4
            [totaltime] => 170.75
            [type] => 0
        )
)

我需要合并employee编号相同的元素,并将totaltime元素添加到基于type. 这就是我的意思。

Array
(
    [0] => Array
        (
            [employee] => 15
            [first_name] => Person1
            [surname] => Person1
            [totaltime_type_0] => 183.75
            [totaltime_type_1] => 64.50

        )       

    [1] => Array
        (
            [employee] => 23
            [first_name] => Person2
            [surname] => Person2
            [totaltime_type_0] => 2.00
            [totaltime_type_1] => 0
        )

    [2] => Array
        (
            [employee] => 51
            [first_name] => Person3 
            [surname] => Person3
            [totaltime_type_0] => 119.25
            [totaltime_type_1] => 0            
        )

    [3] => Array
        (
            [employee] => 59
            [first_name] => Person4
            [surname] => Person4
            [totaltime_type_0] => 170.75
            [totaltime_type_1] => 0
        )
)

我可以在查询级别执行此操作,但创建原始数组的 SQL 非常复杂,我宁愿只维护它的一个版本。

任何关于最佳方法的建议都会真正帮助我重回正轨。并且将不胜感激。

4

1 回答 1

2

试试这个 :

$res      = array();
foreach($your_array as $val){
   $res[$val['employee']]['employee']         = $val['employee'];
   $res[$val['employee']]['first_name']       = $val['first_name'];
   $res[$val['employee']]['surname']          = $val['surname'];
   if($val['type'] == 0){
      if(array_key_exists("totaltime_type_0",$res[$val['employee']])){
         $res[$val['employee']]['totaltime_type_0'] += $val['totaltime'];
      }
      else{
         $res[$val['employee']]['totaltime_type_0'] = $val['totaltime'];
      }
   }
   if($val['type'] == 1){
      if(array_key_exists("totaltime_type_1",$res[$val['employee']])){
         $res[$val['employee']]['totaltime_type_1'] += $val['totaltime'];
      }
      else{
         $res[$val['employee']]['totaltime_type_1'] = $val['totaltime'];
      }
   }
}

echo "<pre>";
print_r(array_values($res));
于 2013-03-28T10:25:43.390 回答