【问题标题】:How to loop over session variables and set new ones if they are set如何循环会话变量并设置新变量(如果已设置)
【发布时间】:2015-02-05 04:43:53
【问题描述】:

基本上我想检查是否设置了一个数字,如果没有设置,则设置它,否则增加数字并设置增加的数字,如果设置了最大数字(12),则退出并抛出错误。逻辑似乎打败了我。

"if is not set *number*, set it;
stop the loop;
else;"

if is set and not empty, number++; 
set the new incremented number;
stop the loop;"

我如何继续循环到三个,我被困在两个上。 "

<?php 
session_start();
//session_destroy();
//exit;


    //////////check if last channel is set//////

if (isset($_SESSION['channel12']) && !empty($_SESSION['channel12'])){
        echo 'You have reached maximum channels for this package';
    } else {
$channels = range(1,12);
$number=0;      

foreach($channels as $channel){
    //$number++;
    $new_channel = $channel + 1;//$number;


    ///////////////Try the first channel and if not set use it/////////
    if (!isset($_SESSION['channel'.$channel.''])){
                    $_SESSION['channel'.$channel.''] = 'channel'.$channel;
                    var_dump($_SESSION);
                break;
                ///////////////Else try next channel/////////
                } else if (isset($_SESSION['channel'.$channel.'']) && !empty($_SESSION['channel'.$channel.''])) {
                    $_SESSION['channel'.$new_channel.''] = $new_channel;
                    var_dump($_SESSION);
                    break;
                    } else {

                        }
}
    }
?>

谢谢。

【问题讨论】:

    标签: php loops foreach session-variables increment


    【解决方案1】:

    试试这个

    <?php
    session_start();
    
    //////////check if last channel is set//////
    if (isset($_SESSION['channel12']) && !empty($_SESSION['channel12'])) {
        echo 'You have reached maximum channels for this package';
    
    } else {
        $channels = range(1, 12);
        $number = 0;
    
        foreach ($channels as $channel) {
            $new_channel = $channel + 1;
            //$number;
    
            ///////////////Try the first channel and if not set use it/////////
            if (!isset($_SESSION['channel' . $channel . ''])) {
                $_SESSION['channel' . $channel . ''] = 'channel' . $channel;
                var_dump($_SESSION);
                break;
                ///////////////Else try next channel/////////
            }
        }
    }
    ?>
    

    【讨论】:

    • 这将在 1 次调用中设置所有变量,每次代码运行时只应设置 1 个变量。
    • 在这种情况下你做错了让我更新代码。
    • 你不明白这个问题。请再读一遍。您必须在第一次加载时将 1 设置为变量,在第二次加载时检查是否 1 isset,如果 isset 设置 2,再次,当脚本运行时,如果设置了 2,则发送变量 3。
    • 在这种情况下,你不需要 else if 和 else inside 循环
    猜你喜欢
    • 2013-03-14
    • 1970-01-01
    • 2021-11-16
    • 1970-01-01
    • 2018-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多