2016-07-20 89 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,但它似乎只適用於'標籤'而不是'分數'。

由於提前

回答

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

只需移動$ output_criterion進入第一foreach循環,像這樣:

<?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;