我的API返回如下:
$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,但它似乎只适用于&#39;标签&#39;不是&#39;得分&#39;。
先谢谢
答案 0 :(得分: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 :(得分:0)
只需将$ output_criterion移动到第一个foreach循环中,如下所示:
npm