如何在不使用另一个数组的情况下删除一个数组中的重复项?

时间:2019-03-30 11:09:41

标签: php arrays for-loop

如何在不使用另一个数组的情况下删除一个数组中的重复项?例如,如果我写星期一,星期三,星期一,星期三(意大利语:lunedì,mercoledì,lunedì,mercoledi),我只需要创建一个包含星期一和星期三的表

我正在考虑将if与boolean一起使用

ps开关盒与一周中的每一天匹配一种颜色

我的代码

body {
  color: purple;
}

table,
th,
td {
  border: 1px solid black;
  width: 44px;
}

#yellow {
  background-color: yellow;
}

#green {
  background-color: green;
}

#orange {
  background-color: orange;
}

#blue {
  background-color: blue;
}

#red {
  background-color: red;
}

#purple {
  background-color: yellowgreen;
}

#royalblue {
  background-color: royalblue;
}
<!DOCTYPE html>
<html>

<head>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Giorni colorati</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" type="text/css" media="screen" href="giornicolorihtml.css">
  <script src="main.js"></script>

</head>

<body>

  <h1> Tabella giorni con colori </h1>

  <form action="giornicolorihtml.php">

    <label>

Scrivi 7 giorni della settimana:

<input type="text" name="giorni" value="">

</label>


    <br>
    <br>
    <br>
    <br>


  </form>

  <?php

$frase = $_GET['giorni'];

$frasespazi=trim($frase);

?>

    <table>

      <tr>

        <?php


          $arrayfrase = explode (",", $frase);

            for ($l=0; $l<count($arrayfrase); $l++) {

              $confronto = $arrayfrase[$l];

                for ($i=count($arrayfrase)-1; $i>0; $i--) {

                    if ($confronto != $arrayfrase[$i]) {


switch (true) {
     case ($arrayfrase[$i] == "lunedì"): $varcolor = "yellow";
        break;
        case ($arrayfrase[$i] == "martedì"): $varcolor = "green";
        break;
        case ($arrayfrase[$i] == "mercoledì"): $varcolor = "orange";
        break;
        case ($arrayfrase[$i] == "giovedì"): $varcolor = "blue";
        break;
        case ($arrayfrase[$i] == "venerdì"): $varcolor = "red";
        break;
        case ($arrayfrase[$i] == "sabato"): $varcolor = "purple";
        break;
        case ($arrayfrase[$i] == "domenica"): $varcolor = "royalblue";
        break;    

    }


}

}
?>

          <td id="<?php echo $varcolor; ?>">
            <?php   
    echo $arrayfrase[$l] ."<br>";

} // for esterno

?>

          </td>

      </tr>

    </table>

</body>

</html>

2 个答案:

答案 0 :(得分:1)

$array = array("Monday", "Wednesday", "Monday", "Wednesday");
$array = array_unique($array); // Array is now ("Monday", "Wednesday")

我希望这行得通

答案 1 :(得分:0)

您可以将重复项与数组中的最后一个元素交换,并从其有效长度中减去1。如果交换,则不会更新当前计数器,但会从“最终”索引中减去1。如果不交换,则更新当前计数器。一旦当前指针大于final,就完成了,并且final之后的元素是重复的。