如何根据条件执行if和else块到if语句块?

时间:2016-06-26 00:36:14

标签: php if-statement

我有一个这样的脚本:

if(isset($_SESSION["LoginValidation"]) && $_SESSION["LoginValidation"] == 1){

    $something = $db->prepare('SELECT cookie FROM users WHERE id = ?');
    $something->execute(array($_SESSION["Id"]));
    $num_row = $something->fetch();
    $_SESSION["cookie"] = $num_row['cookie'];

    if ( $_SESSION["cookie"] != $_COOKIE['login']) ){
        // jump to following else statement (outer else statement)
    }

} else {
    /* here - this block should be execute when
         - That inner if-statement is true
         OR
         - That outer if-statement is false
    */
}

如您所见,我需要执行if - 语句,如果内部if - 语句为true,则执行else - 语句。我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

我认为这是一个算法问题,而不是PHP。无论如何,有几种方法可以做。例如:

$innerCondition = false;
$outerCondition = false;

if(isset($_SESSION["LoginValidation"]) && $_SESSION["LoginValidation"] == 1) {
    $outerCondition = true;
    // ...

    if ($_SESSION["cookie"] != $_COOKIE['login']) {
      $innerCondition = true;
      // ...
    }

} 

if ($innerCondition || !$outerCondition) {
   // ...
} 

答案 1 :(得分:0)

尝试这样的事情:

$doElse = true;
if(isset($_SESSION["LoginValidation"]) && $_SESSION["LoginValidation"] == 1){

    $doElse = false;
    $something = $db->prepare('SELECT cookie FROM users WHERE id = ?');
    $something->execute(array($_SESSION["Id"]));
    $num_row = $something->fetch();
    $_SESSION["cookie"] = $num_row['cookie'];

    if ( $_SESSION["cookie"] != $_COOKIE['login']) ){
        $doElse = true;
    }
    else {
        //rest of the logic
    }

} 

if ($doElse) {
    // here - this block should be execute when inner if-statement is true
}