我尝试了大约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太复杂了,我宁愿只维护它的一个版本。
任何关于最佳方法的建议都能帮助我回到正轨。我真的很感激。试试这个:
$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));