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.

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

报告相同问题?

悬赏问题

  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上