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

如何在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 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛