Foreach 2语句及其内部

时间:2019-07-20 09:53:19

标签: php foreach

  

您好,先生,我真的是php新手

我需要回答一个问题,并检查是否与关键答案相同,或者不使用array和foreach。看看他有多少正确答案

但是我不能在foreach中使用2条语句。 先生,请帮我,谢谢

<?php

$x=0;
foreach ($_POST['answer'] as $answer & $_POST['key'] as $key) {
	if($answer = $key){
	$x+1;
	}
	
}
echo $x;
 ?>

<form name="coba" method="post" action="cobaradio.php" />

<p><i>Rate each question from 6 to 1, six being strongly 
agree and one being strongly disagree.</i></p>

1. I think the module guide/student handbook provided enough information about the 
module content, organisation and assessment.<br/>

6<input type="radio" name="answer[0]" value="6"> 5<input type="radio" name="answer[0]" value="5"> 
4<input type="radio" name="answer[0]" value="4"> 3<input type="radio" name="answer[0]" value="3"> 
2<input type="radio" name="answer[0]" value="2"> 0<input type="radio" name="answer[0]" value="0">
<input type="hidden" name="key[0]" value="2">
</p>
<p><i>Rate each question from 6 to 1, six being strongly 
agree and one being strongly disagree.</i></p>

1. I think the module guide/student handbook provided enough information about the 
module content, organisation and assessment.<br/>

1<input type="radio" name="answer[1]" value="1"> 4<input type="radio" name="answer[1]" value="4"> 
2<input type="radio" name="answer[1]" value="2"> 5<input type="radio" name="answer[1]" value="5"> 
3<input type="radio" name="answer[1]" value="3"> 6<input type="radio" name="answer[1]" value="6">
<input type="hidden" name="key[1]" value="3">
</p>
<button type="submit" name="waha">Tekan</button>
</form>

3 个答案:

答案 0 :(得分:0)

假设$_POST['answer']$_POST['key']上的索引匹配:

$rightAnswers = 0;

foreach ($_POST['answer'] as $index => $answer) {
    if ($answer = $_POST['key'][$index]) {
        $rightAnswers++;
    }
}

echo $rightAnswers . ' right answers';

答案 1 :(得分:0)

示例1:

<?php

$x=0;
foreach ($_POST['answer'] as $answer) {
    if(in_array($answer, $_POST['key'])){
        $x++;
    }
}
echo $x;
?>

示例2:

<?php
$res = array_intersect($_POST['answer'], $_POST['key']);
echo count($res);
?>

答案 2 :(得分:0)


<?php

$x = 0;
$_POST['answer'] = array(1, 2, 3, 4, 5);
$_POST['key']    = array(1, 7, 6, 43, 5);

array_map(function ($n, $m) use (&$x) {
    if ($n == $m) {
        $x++;
    }
}, $_POST['answer'], $_POST['key']);

echo $x;//2