有这样的数组:
array (
'@attributes' =>
array (
'status' => 'ok',
),
'time_entries' =>
array (
'@attributes' =>
array (
'page' => '1',
'per_page' => '100',
'pages' => '1',
'total' => '33',
),
'time_entry' =>
array (
0 =>
array (
'time_entry_id' => '1411884',
'staff_id' => '22384',
'project_id' => '11116',
'task_id' => '3296',
'hours' => '1.75',
'date' => '2017-02-20',
'notes' => 'What is Quadra, Events Slider, Event Page Setup',
'billed' => '0',
),
1 =>
array (
'time_entry_id' => '1411254',
'staff_id' => '22384',
'project_id' => '11116',
'task_id' => '3296',
'hours' => '1.5',
'date' => '2017-02-17',
'notes' => 'Events Slider, Background overlay, Intro',
'billed' => '0',
),
2 =>
array (
'time_entry_id' => '1410694',
'staff_id' => '22384',
'project_id' => '11116',
'task_id' => '3296',
'hours' => '2.75',
'date' => '2017-02-16',
'notes' => 'Background Image SVGs, Header, Footer',
'billed' => '0',
),
3 =>
array (
'time_entry_id' => '1410586',
'staff_id' => '22384',
'project_id' => '11116',
'task_id' => '3296',
'hours' => '0.5',
'date' => '2017-02-15',
'notes' => 'Site Background
Assign Less Variables',
'billed' => '0',
),
4 =>
array (
'time_entry_id' => '1409621',
'staff_id' => '22384',
'project_id' => '11116',
'task_id' => '3296',
'hours' => '0.25',
'date' => '2017-02-14',
'notes' => 'Theme Install',
'billed' => '0',
),
...它实际上比第一个更进一步4.我要做的是通过键[“task_id”]对这些数组进行排序,以便我可以将它们组合在一起,然后将[“小时”加在一起“]键 - 这样我最终可以输出每个task_id下的总工作小时数。
我尝试了一些'array_merge_recursive'和类似但我不知所措;这是PHP比我的水平高一点。非常感谢。
答案 0 :(得分:1)
因此,通过生成一组新数据而不是尝试修改此数组,您可能最好通过总和进行求和。
这样的东西会给你你想要的东西:
$time_entries = $your_array["time_entries"]["time_entry"];
$task_hours = [];
foreach ($time_entries as $time_entry) {
if (!isset($task_hours[$time_entry["task_id"]])) {
$task_hours[$time_entry["task_id"]] = 0;
}
$task_hours[$time_entry["task_id"]] += (float) $time_entry["hours"];
}
$task_hours
会给你一个像:
Array
(
[3296] => 5
[1879] => 0.25
)
答案 1 :(得分:0)
而不是对数组进行排序,然后总结小时,以便不处理该数组的相关部分并一次性完成求和。
ConstraintLayout
您现在应该有一个数组,其中键是$tots = array();
foreach( $array['time_entry'] as $task ) {
if ( isset($tots['task_id']) ) {
$tots['task_id'] += $task['hours'];
} else {
$tots['task_id'] = $task['hours'];
}
}
,其值是所有键task_id
的总和。
如果您想按顺序排列hours
,那么在输出任何结果之前对task_id
数组进行排序
$tots
如果您希望结果按照小时数的顺序
ksort($tots);