![](/img/trans.png)
[英]Multidimensional result array need to merge in single with same key value using PHP
[英]Same content value need to sum in- multidimensional array - using PHP
我有一個包含數組對象數目的數組的多維結果,需要將此結果合並到具有唯一值的content
和total
的array的單個實例中。 像下面期望的結果。 幫助肯定是贊賞。
結果集
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.