douluan5738
douluan5738
2017-02-23 21:05

重复if / elseif / else完成

已采纳

I'd like to be able to loop the if/elseif/else statement if it falls onto any of the statement that is not else.

$names is an array with a couple of names that the user will select.

Right now, the code does work but if the condition falls into any of the elseifs then the loop will stop. From the user's perspective it's almost like nothing has happened.

if($names[0] == $poster) {
    shuffle($names);   
} elseif($names[1] == $entertainer) {
    shuffle($names);         
} elseif($names[2] == $tunar) {
    shuffle($names);        
} elseif($names[3] == $keeper) {
    shuffle($names);        
} elseif($names[4] == $feeder) {
    shuffle($names);    
} elseif($names[5] == $provider) {
    shuffle($names);
} else {
    echo "This week's roles are:";

    while($row = mysqli_fetch_assoc($this_week_result) ) {
                $poster = $row['poster'];
                $entertainer = $row['entertainer'];
                $tunar = $row['tunar'];
                $keeper = $row['keeper'];
                $feeder = $row['feeder'];
                $provider = $row['provider'];
    }

        echo $names[0] . " is the Poster <br>";
        echo $names[1] . " is the Entertainer <br>";
        echo $names[2] . " is the Tunar <br>";
        echo $names[3] . " is the Keeper <br>";
        echo $names[4] . " is the Feeder <br>";
        echo $names[5] . " is the Provider <br>";

        $sql = "INSERT INTO funroles 
        (poster,entertainer,tunar, keeper, feeder, provider, date)
        VALUES ('$names[0]','$names[1]','$names[2]','$names[3]','$names[4]','$names[5]','$date')";

        $result = mysqli_query($conn, $sql);
        mysqli_close($conn);
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • doujiao3072 doujiao3072 4年前

    It looks like you want to keep shuffling until none of the names in $names is in the same position it previously was. If I understand it correctly, you can do it without the if/elseif/else structure.

    Create an array of the current names that matches the key position of $names like this:

    $current = [$poster, $entertainer, $tunar, $keeper, $feeder, $provider];
    

    Then use array_intersect_assoc to check if any key/value pairs match, and shuffle until none of them do (it will return an empty array).

    while (array_intersect_assoc($current, $names)) {
        shuffle($names);
    }
    

    Then do the stuff with your database afterward.

    点赞 评论 复制链接分享