PHP——如何在while循环中检查条件?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (35)

这个$noOfSeat变量值是11。

这会foreach返回10,8,12。

foreach ($_POST['vid'] as $key => $value) {
    $assign->get('vehicle', ['noOfSeat'], ['vid', '=', $value]);
    $dataSeat = $assign->result->fetch_assoc();
    echo $noOfSeat_p = $dataSeat['noOfSeat'];
}

如果在第一个循环中11小于10 如果没有,则显示错误消息,然后检查第二个循环如果11 <18(10 + 8)如果为真则停止,否则显示错误消息并运行第三个循环。

提问于
用户回答回答于
<?php 

$_POST['vid'] = [1, 2, 3];
$vehicles = [
    1 => [
        'noOfSeat' => 10,
    ],
    2 => [
        'noOfSeat' => 8,
    ],
    3 => [
        'noOfSeat' => 12,
    ]
];
$totalSeatsCount = 0;
$needSeats = 18;
$lastIteration = count($_POST['vid']) - 1;
$i = 0;
foreach ($_POST['vid'] as $key => $value) {
    // $assign->get('vehicle', ['noOfSeat'], ['vid', '=', $value]);
    // $dataSeat = $assign->result->fetch_assoc();
    $dataSeat = $vehicles[$value];
    $totalSeatsCount += $dataSeat['noOfSeat'];
    if ($totalSeatsCount < $needSeats) {
        echo "error" . PHP_EOL;
    } elseif ($i < $lastIteration) {
        echo "too many vid in request" . PHP_EOL;
        break;
    } else {
        echo "it's ok" . PHP_EOL;
    }
    $i++;
}
用户回答回答于
<?php
$sum = 0;
foreach ($_POST['vid'] as $key => $value) {
    $sum += $value;
    if ($sum < 11) {
        echo 'ERROR MESSAGE';
        break;
    }
    $assign->get('vehicle', ['noOfSeat'], ['vid', '=', $value]);
    $dataSeat = $assign->result->fetch_assoc();
    echo $noOfSeat_p = $dataSeat['noOfSeat'];
}

扫码关注云+社区

领取腾讯云代金券