数组和每个函数不起作用

时间:2015-11-21 22:21:35

标签: php arrays variables foreach get

请有人帮助我,我正在尝试使用数组函数根据复选框的结果给出整体变量的正值或负值。

复选框问题是,存在以下哪个驯鹿,所以对于每个正确的驯鹿我都希望给变量$ finalvalue一个增量值。然后在末尾留下一个IF函数来说明是否勾选了错误的驯鹿,给出一个减量值,但是还有正确值的增量值。

我已经附上了下面的代码,每次使用时,价值都没有按照需要增加,或者不是每个正确的驯鹿都累积。

感谢。

HTML FIRST

Which of the following are of Santa's Reindeer?(You can select more than one answer)<br>

<input type="checkbox" name="reindeer" value="Rudolph">Rudolph<br>
<input type="checkbox" name="reindeer" value="Prancer">Prancer<br>
<input type="checkbox" name="reindeer" value="Dancer">Dancer<br>
<input type="checkbox" name="reindeer" value="Ronald">Ronald<br>

<br><br>
<input type="submit" value="Submit">

PHP SCRIPT RECIEVER SIDE

$reindeer=$_GET['reindeer'];

$type=array("Rudolph","Dancer","Prancer");
foreach($type as $reindeer){$finalvalue = $finalvalue+2;};

if ($reindeer=="Donald"){$finalvalue = $finalvalue-6;}


print "$finalvalue";

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

<?php

    $input = $_GET['reindeer'];
    $valid = ["Rudolph","Dancer","Prancer"];

    # Debug input..
    echo 'Raw input data:<pre>';
    var_dump($input);
    echo '</pre>';


    if(is_array($input)){
        foreach($input as $reindeer){
            if(in_array($reindeer, $valid)){
                echo 'user supplied multiple answers and '.$reindeer.' is listed in $valid. </br>';
                $finalvalue = $finalvalue+2;
            } else {
                echo 'user supplied multiple answers and '.$reindeer.' is listed <strong>not</strong> in $valid. </br>';
                $finalvalue = $finalvalue-6;
            }
        }
    } else {
        # This code should never execute unless the user changes the html code.
        if(in_array($input, $valid)){
            echo 'user supplied 1 answer and '.$reindeer.' is listed in $valid. </br>';
            $finalvalue = 2;
        } else {
            echo 'user supplied 1 answer and '.$reindeer.' is listed <strong>not</strong> in $valid. </br>';
            $finalvalue = 0;
        }
    }


    echo $finalvalue;

?>

答案 1 :(得分:0)

Which of the following are of Santa's Reindeer?(You can select more than one answer)<br>

<input type="checkbox" name="reindeer[]" value="Rudolph">Rudolph<br>
<input type="checkbox" name="reindeer[]" value="Prancer">Prancer<br>
<input type="checkbox" name="reindeer[]" value="Dancer">Dancer<br>
<input type="checkbox" name="reindeer[]" value="Ronald">Ronald<br>

<br><br>
<input type="submit" value="Submit">



 $input = $_GET['reindeer'];
 $valid = ["Rudolph","Dancer","Prancer"];


 foreach($input as $reindeer){
      if(in_array($reindeer, $valid)){
            $finalvalue = $finalvalue+2;
       } else {
            $finalvalue = $finalvalue-6;
       }
  }

注意html中的括号。将这些括号添加到输入的名称使其成为一个数组。因此,产生更清洁和最少的代码。