如何在foreach循环中创建变量并在循环外使用它?

时间:2016-08-10 11:00:03

标签: php xml foreach

我将输入的2个数字与xml文件中的数字进行比较,然后将每个比较的结果存储在变量($ n1,$ n2)中。然后我将每个变量的总和添加到foreach循环中的新变量$ total中。我已经尝试在循环中显示结果,但它显示了正确和错误比较的结果,因为它循环遍历整个xml。

我希望能够在循环外部使用$ total来显示结果。当我在循环外回显$ total时,无论比较是否正确,其结果为0。当我在循环中回显它时它有一个值。

如何确保$ total变量将其存储值保持在循环之外?

$num1 = $_POST['num1'];
$num2 = $_POST['num2'];

$xml = simplexml_load_file('lottery2.xml') or die("Error: Cannot create object");
if(isset($_POST['num1'])&& isset($_POST['num2']))
{
foreach($xml->children() as $record)
{ 
    if($record->num1 == $num1 || $record->num2 == $num1) 
     {
        $n1=1;
     } 
    else 
     {
        $n1=0;
     }
    if($record->num1 == $num2 || $record->num2 == $num2) 
     {
        $n2=1;
     } 
    else 
     {
        $n2=0;
     }

    $total= $n1+$n2;

}//end foreach

    if ($total=2) {
        echo "Jackpot is ".$record->jackpot ."<br />";
    } else {
        echo "No jackpot, sorry";
    }

3 个答案:

答案 0 :(得分:0)

如果您关心的是两个号码是否都找到了,请使用布尔值(不需要$total):

$n1 = false;//make true once we find 1st num
$n2 = false;//make true once we find 2nd num
foreach($xml->children() as $record){
    $n1 = $n1 || $record->num1 == $num1 || $record->num2 == $num1;
    $n2 = $n2 || $record->num1 == $num2 || $record->num2 == $num2;

    if($n1 && $n2) break; //we've found both. No need to keep looking
}//end foreach

if ($n1 && $n2) echo "Jackpot!";
else echo "No Jackpot, sorry";

答案 1 :(得分:0)

更改

if ($total=2)

if ($total == 2)

答案 2 :(得分:0)

在循环之外声明它

 $num1 = $_POST['num1'];
$num2 = $_POST['num2'];
$total=0;

并连接值。

 $total+=$num1+$num2;