douluan5738 2017-02-23 21:05
浏览 54
已采纳

重复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 2017-02-23 22:11
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 arduino控制ps2手柄一直报错
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 求chat4.0解答一道线性规划题,用lingo编程运行,第一问要求写出数学模型和lingo语言编程模型,第二问第三问解答就行,我的ddl要到了谁来求了
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题