猿问

为不同的数组值创建 SWITCH 案例

如何编写 SWITCH 案例的代码以给出 x 和 y 数值?x 和 y 在一个数组中。数组中的数据来自数据库。


<?php

        $main_link = mysqli_connect('localhost', 'root', '','WMYC');

        $a1 = mysqli_fetch_array(mysqli_query($main_link, "SELECT * FROM teams WHERE team='t1' AND round='r1'"));

        $b1 = mysqli_fetch_array(mysqli_query($main_link, "SELECT * FROM teams WHERE team='t2' AND round='r1'"));

        $c1 = mysqli_fetch_array(mysqli_query($main_link, "SELECT * FROM teams WHERE team='t3' AND round='r1'"));

        $d1 = mysqli_fetch_array(mysqli_query($main_link, "SELECT * FROM teams WHERE team='t4' AND round='r1'"));

        $array = array($a1['xy'], $b1['xy'], $c1['xy'], $d1['xy']);

        print_r($array); // will get Array ( [0] => x [1] => y [2] => x [3] => x ) 

        print_r(array_count_values($array)); // will get Array ( [x] => 3 [y] => 1 )


    switch(isset($_POST['round1']))

    {

            case //array_count_values($array) == ( [x] => 3 [y] => 1 ):

          //value of x = 1 and value of y= -3

            break;

            case //array_count_values($array) == ( [x] => 2 [y] => 2 ):

          //value of x = 2 and value of y= -2

            break;

            case //array_count_values($array) == ( [x] => 1 [y] => 3 ):

          //value of x = 3 and value of y= -1

            break;

            case //array_count_values($array) == ( [x] => 4 ):

          //value of x = -1

            break;

            case //array_count_values($array) == ( [y] => 4 ):

          //value of y = 1

    }

        ?>

如果有比 switch case 更好更简单的方法请指教


动漫人物
浏览 88回答 2
2回答

手掌心

由于计数将始终加起来为 4,因此您无需比较整个数组,只需获取计数x并在switch语句中使用它即可。$counts = array_count_values($array);if (isset($_POST['round1'])) {&nbsp; &nbsp; switch (@$counts['x']) {&nbsp; &nbsp; case 3:&nbsp; &nbsp; &nbsp; &nbsp; // do something for x=3 y=1&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; case 2:&nbsp; &nbsp; &nbsp; &nbsp; // do something for x=2 y=2&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; case 1:&nbsp; &nbsp; &nbsp; &nbsp; // do something for x=1 y=3&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; default:&nbsp; &nbsp; &nbsp; &nbsp; // do something for x=0 y=4}当计数为时, @before会$counts['x']抑制警告(因为数组中0不会有元素);x然后我们进入这个default:案子。

杨__羊羊

您错误地使用了 switch 语句。Switch 表示,基于 switch() 中的值,根据其值(case 语句)执行一些代码。所以你所说的:switch(isset($_POST['round1'])) 是基于现有的 $_POST['round1'] 的价值,做点什么。isset 返回真/假。如果 $_POST['round1'] 存在,它将返回 true,否则将返回 false。你不想在这里使用 switch 语句,你想使用 if / else。if (array_count_values($array) == ( [x] => 3 [y] => 1 ) {&nbsp; //do something}elseif (array_count_values($array) == ( [x] => 2 [y] => 2 ) {&nbsp; //do something}$_POST['round1'] isset 是否似乎对您的代码没有任何影响,但如果它很重要,您可以执行以下操作:if (isset($_POST['round1'])) {&nbsp; if (array_count_values($array) == ( [x] => 3 [y] => 1 ) {&nbsp; &nbsp; //do something&nbsp; }&nbsp; elseif (array_count_values($array) == ( [x] => 2 [y] => 2 ) {&nbsp; &nbsp; //do something&nbsp; }}else {&nbsp; //handle $_POST['round1'] not being set}
随时随地看视频慕课网APP
我要回答