2016-07-20 91 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;