【问题标题】:Getting only values that are not the same as the values in an array仅获取与数组中的值不同的值
【发布时间】:2021-05-08 11:08:47
【问题描述】:

我正在尝试运行一个 for 循环来检查数组中的所有值,然后运行 ​​if 语句,如果任何值与数组中的值匹配,它将跳过该值。 我有这个:

总座位数

 10
$seats_arr = [1, 4, 7]
$result = mysqli_query($con, "SELECT * FROM trains WHERE id='$id'");

while ($row = mysqli_fetch_array($result)) {
    $total_seats = $row['seats'];
    $booked_seats = $row['booked_seats'];
    $viti = $row['viti'];
         
    $seats_arr = preg_split("/\,/", $viti);
    print_r($seats_arr);
                    
    ?>
    
    <select class="custom-select col-12" name="selected_seat">
        <option selected="" disabled>Choose your seat</option>
        <?php
         $N = $total_seats;
         foreach ($seats_arr as $seat) {            
         for($i=1; $i <= $N; $i++) {
                     
            if($i == $seat){
                continue;
             }
                      
         ?>
         <option value="<?php echo $i; ?>"><?php echo "Seat ", $i; ?></option>
          <?php
               } 
             }
           }
         ?>
     </select>

期望的输出

2, 3, 5, 6, 8, 9, 10

【问题讨论】:

  • 发布数组样本和所需输出
  • 首先 foreach ($seats_arr as $food) 将其值存储在 $food 中,并且在循环内不调用此变量。其次,foreach 中的 for 循环是不必要的。尝试更明确地寻求帮助
  • 警告:您对SQL Injections 持开放态度,应该使用参数化的prepared statements,而不是手动构建查询。它们由PDOMySQLi 提供。永远不要相信任何形式的输入!即使您的查询仅由受信任的用户执行,you are still in risk of corrupting your dataEscaping is not enough!

标签: php for-loop


【解决方案1】:

既然你只是在处理数字......这应该可以正常工作

$range = range(1,$total_seats);
$seats_arr = [1, 4, 7];

$newunselected = array_diff($range,$seats_arr); //Your new array you can foreach this

print_r($newunselected); 

【讨论】:

    猜你喜欢
    • 2012-09-19
    • 2015-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多