2016-05-03 11 views
0

私は配列オブジェクトの数を含む配列の多次元結果を持っており、この結果を一意の値contentと合計でtotalの配列の単一インスタンスにマージする必要があります。希望の結果のように。助けは間違いなく評価されます。同じ内容の値が多次元配列を合計する必要があります - PHPを使用

結果セット

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; 
}); 

答えて

1

ループはこのようです...少し厄介ですが動作するはずです。

もちろん、最適化の余地がたくさんありますが、それを改善する方法はあなた次第です。

$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 
のようなものです
0

行うには、ネイティブメソッドはありませんティあなた自身で書いてください。

$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);