dsfsw1233 2016-08-10 11:00
浏览 218
已采纳

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

I'm comparing 2 numbers entered to numbers in an xml file and then storing the result of each comparison in a variable ($n1, $n2). I'm then adding the total of each variable up and storing it in a new variable $total within the foreach loop. I've tried displaying the result in the loop but it shows both the result for correct and incorrect comparison as it loops around the whole xml.

I want to be able to use $total outside of the loop to display a result. When I echo $total outside the loop, its result is 0 no matter whether the comparisons are correct. When I echo it in the loop it has a value.

How to I ensure the $total variable keeps its stored value outside of the loop?

$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条回答 默认 最新

  • dryk50495 2016-08-10 11:02
    关注

    If all you care about is whether both numbers were found, use booleans (no need for $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";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 鼠标右键,撤销删除 复制 移动,要怎样删除
  • ¥15 使用MATLAB进行余弦相似度计算加速
  • ¥15 服务器安装php5.6版本
  • ¥15 我想用51单片机和数码管做一个从0开始的计数表 我写了一串代码 但是放到单片机里面数码管只闪烁一下然后熄灭
  • ¥20 系统工程中,状态空间模型中状态方程的应用。请猛男来完整讲一下下面所有问题
  • ¥15 我想在WPF的Model Code中获取ViewModel Code中的一个参数
  • ¥15 arcgis处理土地利用道路 建筑 林地分类
  • ¥20 使用visual studio 工具用C++语音,调用openslsx库读取excel文件的sheet问题
  • ¥100 寻会做云闪付tn转h5支付链接的技术
  • ¥15 DockerSwarm跨节点无法访问问题