我有一个数组的多维结果,其中包含多个数组对象,需要将该结果合并到具有唯一值content
和total
的数组的单个实例中。如以下所需结果。我们非常感谢您的帮助。
结果集
Array
(
[0] => Array
(
[response_id] => 23598
[choice_question_detail] => Array
(
[0] => Array
(
[content] => How old are your.
[total] => 5
)
[1] => Array
(
[content] => Stadium.
[total] => 4
)
),
[1] => Array
(
[response_id] => 23599
[choice_question_detail] => Array
(
[0] => Array
(
[content] => How old are your.
[total] => 2
)
[1] => Array
(
[content] => Stadium.
[total] => 1
)
)
)
期望结果
Array
(
[0] => Array
(
[content] => How old are your.
[total] => 7
)
[1] => Array
(
[content] => Stadium.
[total] => 5
)
)
我目前的实现尝试这样做:
$sum = array_reduce($data, function ($a, $b) {
isset($a[$b['choice_question_detail']]) ? $a[$b['choice_question_detail']]['total'] += $b['total'] : $a[$b['total']] = $b;
return $a;
});
循环如下。。。有点恶心,但应该行得通。
当然还有很大的优化空间,如何改进它取决于你
$out = array();
foreach($var as $row) {
foreach($row['choice_question_detail'] as $detail) {
$flag = false;
$numkey = -1;
foreach($out as $key => $x) {
if($x['content'] == $detail['content']) {
$flag = true;
$numkey = $key;
}
}
if(!$flag) {
$out[] = array(
'content' => $detail['content'],
'total' => $detail['total']
);
} else {
$out[$numkey]['total'] = $out[$numkey]['total'] + $detail['total'];
}
}
}
输出类似于
array (size=2)
0 => array (size=2)
'content' => string 'How old are your.' (length=17)
'total' => int 7
1 => array (size=2)
'content' => string 'What is your name.' (length=18)
'total' => int 5
没有本地方法可以做到这一点,请自己编写。
$merged = array();
foreach($responses["choice_question_detail"] as $question){
if($merged_q=$merged[$question["content"]]){
$merged_q["total"] += $question["total"];
}else{
$merged[$question["content"]] = $qeustion;
}
}
$desired = array_values($merged);