Array
(
[0] => Array
(
[datas] => Array
(
[name] => lorem
[id] => 1
[type] => t1
[due_type] => Q1
[t1] => 1
[t2] => 1
[t3] => 1
)
)
[1] => Array
(
[datas] => Array
(
[name] => lorem
[id] => 1
[type] => t2
[due_type] => Q1
[t1] => 0
[t2] => 1
[t3] => 0
)
)
[2] => Array
(
[datas] => Array
(
[name] => name
[id] => 2
[type] => t1
[due_type] => Q1
[t1] => 1
[t2] => 0
[t3] => 1
)
)
[3] => Array
(
[datas] => Array
(
[name] => name
[id] => 2
[type] => t2
[due_type] => Q1
[t1] => 1
[t2] => 0
[t3] => 0
)
)
)
我想根据其id添加每个数组的值,但是我在使用这些代码获取值时遇到问题:我想根据每个类型的总和> due_type 并将它们组合成一个数组。
$totals = array();
$i = -1;
foreach($datas as $key => $row){
$i += 1;
$items[$i] = $row;
if (isset($totals[$items[$i]['datas']['id']])){
if($totals[$items[$i]['datas']['id']]['due_type'] == 'Q1'){
if($totals[$items[$i]['datas']['id']]['type'] == 't1'){
$t1+=$totals[$items[$i]['datas']['id']]['t1'];
}elseif($totals[$items[$i]['datas']['id']]['type'] == 't2'){
$t2+=$totals[$items[$i]['datas']['id']]['t2'];
}elseif($totals[$items[$i]['datas']['id']]['type'] == 't3'){
$t3+=$totals[$items[$i]['datas']['id']]['t3'];
}
$totals[$items[$i]['datas']['id']]['t1_total'] = $t1;
$totals[$items[$i]['datas']['id']]['t2_total'] = $t2;
}
}
else {
$totals[$items[$i]['datas']['id']] = $row['datas'];
$totals[$items[$i]['datas']['id']]['t1_total'] = $items[$i]['datas']['t1'];
$totals[$items[$i]['datas']['id']]['t2_total'] = $items[$i]['datas']['t2'];
}
}
答案 0 :(得分:1)
不确定您想要的输出,但是:
function condense($data, $condensed = array()) {
foreach($data as $row) {
$id = $row['datas']['id'];
$due_type = $row['datas']['due_type'];
$type = $row['datas']['type'];
if(!array_key_exists($id, $condensed)) {
$condensed[$id] = array();
}
if(!array_key_exists($due_type, $condensed[$id])) {
$condensed[$id][$due_type] = array();
}
if(!array_key_exists($type, $condensed[$id][$due_type])) {
$condensed[$id][$due_type][$type] = 0;
}
$condensed[$id][$due_type][$type] += $row['datas'][$type];
}
return $condensed;
}
$result = condense($data);
给你:
Array
(
[1] => Array
(
[Q1] => Array
(
[t1] => 1
[t2] => 1
)
)
[2] => Array
(
[Q1] => Array
(
[t1] => 1
[t2] => 0
)
)
)
答案 1 :(得分:0)
我可能错了,但感觉就像是从数据库读取这些数组。在数据库本身中执行此类操作可能更容易:
像这样的SQL语句可以执行您要执行的操作:
SELECT count(1),type,due_type FROM Table GROUP BY type, due_type;
您可以在PHP中阅读输出。