我遇到了执行嵌套的foreach循环执行以获得所需结果的问题。以下是场景:
以下是两个数组的结果
结果1:
Array ( [0]=> Array ( [questionID] => 103 [answer] => Female [answer_cnt] => 8 )
[1] => Array ( [questionID] => 103 [answer] => Male [answer_cnt] => 9 )
)
结果2
Array ( [0] => Male [1] => Female )
我使用foreach循环的代码在
之下 foreach($qrs as $qrow)
{ foreach($d as $q){
echo"<br>".$q;
echo $qrow['answer_cnt']."<br>";}
}
它将获得输出:
Male 8
Female8
Male 9
Female9
但我的预期输出是
Female 8
Male 9
答案 0 :(得分:1)
你不需要循环第二个。只需使用第一个。
foreach($qrs as $qrow) {
echo $qrow['answer'] . ' ' . $qrow['answer_cnt'] . '<br/>';
}
目前还不清楚为什么你需要第二个数组,但是如果你想要包含它(没有意义),只需要包含一个if。
foreach($qrs as $qrow) {
foreach($d as $q) {
if($qrow['answer'] == $q) {
echo $qrow['answer'] . ' ' . $qrow['answer_cnt'] . '<br/>';
}
}
}
答案 1 :(得分:0)
你的第二个阵列没用。只是做:
foreach($qrs as $qrow)
{
echo"<br>".$qrow['answer']." ";
echo $qrow['answer_cnt']."<br>";}
}
答案 2 :(得分:0)
使用此...
foreach($qrs as $qrow)
{
foreach($d as $q)
{
if(in_array($q, $qrow))
{
echo"<br>".$q;
echo $qrow['answer_cnt']."<br>";
}
}
}
答案 3 :(得分:0)
$arr = array(
array( 'questionID' => 103, 'answer' => 'Female', 'answer_cnt' => 8),
array( 'questionID' => 103, 'answer' => 'Male', 'answer_cnt' => 9)
);
if(count($arr) > 0) {
foreach($arr as $val) {
echo "$val[answer] $val[answer_cnt] <br />";
}
}
你也可以试试这个。