2016-07-20 15 views
3

私は以下のように返すAPIを持っています。PHP - foreachの重複問題

$arrays = array(
    "1" => array(
     "name" => "Mike", 
     "date" => "1/2/2016", 
     "criterion" => array(
      "1" => array(
        "label" => "Value for Money", 
        "scores" => "5" 
       ), 
      "2" => array(
        "label" => "Policy Features And Benefits", 
        "scores" => "1.5" 
       ), 
      "3" => array(
        "label" => "Customer Service", 
        "scores" => "3" 
       ) 

     ) 
    ), 
    "2" => array(
     "name" => "Megu", 
     "date" => "1/2/2015", 
     "criterion" => array(
      "1" => array(
        "label" => "Value for Money", 
        "scores" => "2" 
       ), 
      "2" => array(
        "label" => "Policy Features And Benefits", 
        "scores" => "3.5" 
       ), 
      "3" => array(
        "label" => "Customer Service", 
        "scores" => "1" 
       ) 

     ) 
    ) 
); 

そしてPHPコード:

$output = ''; 
$output_criterion = ''; 

foreach($arrays as $a){ 

    $criterions_arr = $a['criterion']; 
    foreach($criterions_arr as $c){ 
     $output_criterion .= $c['label'] . ' - ' . $c['scores'] . '<br/>'; 
    } 

    $output .= $a['name'] . '<br/>' . $output_criterion . '<br/>'; 

} 

echo $output; 

結果:私はに結果を希望しかし

Mike 
Value for Money - 5 
Policy Features And Benefits - 1.5 
Customer Service - 3 

Megu 
Value for Money - 5 
Policy Features And Benefits - 1.5 
Customer Service - 3 
Value for Money - 2 
Policy Features And Benefits - 3.5 
Customer Service - 1 

ネストされたforeachループで重複することなく以下のようになります。

Mike 
Value for Money - 5 
Policy Features And Benefits - 1.5 
Customer Service - 3 

Megu 
Value for Money - 2 
Policy Features And Benefits - 3.5 
Customer Service - 1 

どうすればいいですか?私はarray_uniqueを使っていますが、 'score'ではなく 'label'でしか動作しないようです。アドバンス

答えて

3

おかげで各外部反復変数$output_criterionをリセットします。以前のすべての値を連結します。

$output = ''; 
foreach($arrays as $a){ 
    $output_criterion = ''; 
    $criterions_arr = $a['criterion']; 
    foreach($criterions_arr as $c){ 
     $output_criterion .= $c['label'] . ' - ' . $c['scores'] . '<br/>'; 
    } 
    $output .= $a['name'] . '<br/>' . $output_criterion . '<br/>'; 
} 
echo $output; 

ライブデモを追加:https://eval.in/608400

+1

良い答えが変更を説明しています。とにかく+1を見つけるために – Thamilan

+0

すごく感謝して、それは簡単です!それを認識していない! – Mike

0

は単純にそうような最初のforeachループの中に$ output_criterionを動かす:

<?php 

     $output     = ''; 

     foreach($arrays as $a){ 
      $criterions_arr  = $a['criterion']; 
      $output_criterion = ''; 
      foreach($criterions_arr as $c){ 
       $output_criterion .= $c['label'] . ' - ' . $c['scores'] . '<br/>'; 
      } 
      $output    .= $a['name'] . '<br/>' . $output_criterion . '<br/>'; 


     } 

     echo $output;