满足特定条件时填充数组

Array being populated when meeting certain condition

我目前正在尝试让关联数组在另一个数组“已满”时取值。有两个 asso 数组代表停车场(一个用于小型车,另一个用于大型车),如果小型车都被占用,则小型车可以停在较大的位置。我得到了这个工作,但我坚持了一点我似乎不明白的逻辑。

小阵有 10 个点,大阵有 14 个。 给我带来麻烦的是 ( $_SESSION['parkingLarge']["spot1"] === 0 && $_SESSION['parkingSmall']["spot10"] === 1) 我知道这是可以预料的,因为当它跳出第一个 foreach 循环时,它将满足下一条语句中的条件,并将最后一个 1 添加到第一个数组中的 spot10,它也会自动将其添加到第一个数组中更大的数组。

有什么方法可以阻止这种行为,或者以更好的方式对此进行编码?

数组是:

$parkingSmall = array(
    "spot1" => 1, "spot2" => 1, "spot3" => 1, "spot4" => 1, "spot5" => 1,
    "spot6" => 1, "spot7" => 1, "spot8" => 1, "spot9" => 0, "spot10" => 0
);

$parkingLarge = array(
    "spot1" => 0, "spot2" => 0, "spot3" => 0, "spot4" => 0, "spot5" => 0,
    "spot6" => 0, "spot7" => 0, "spot8" => 0, "spot9" => 0, "spot10" => 0,
    "spot11" => 0, "spot12" => 0, "spot13" => 0, "spot14" => 0
);

$_SESSION['parkingSmall'] = $parkingSmall;
$_SESSION['parkingLarge'] = $parkingLarge;

代码

if ($_POST["size"] == 'small') {

    foreach ($_SESSION['parkingSmall'] as $key => $value) {
        if ($value === 0) {
            $_SESSION['parkingSmall'][$key] = 1;
            echo "Car parked";
            break;
        }
    }
    if ( $_SESSION['parkingLarge']["spot1"] === 0 && $_SESSION['parkingSmall']["spot10"] === 1) {
        foreach ($_SESSION['parkingLarge'] as $key => $value) {
            if ($value === 0) {
                $_SESSION['parkingLarge'][$key] = 1;
                echo "Small car parked in large spot";
                break;
            }
        }
    }
    if ($_SESSION['parkingLarge']["spot14"] === 1) {
        echo "No more spaces available in both parkings";
        return false;
    }
}

非常欢迎对此提供任何帮助!!!

对于这种情况,您可以使用 array_search,例如:

$type = 'small';
$key = array_search(0, $_SESSION['parkingSmall']) ?: null;
if (!$key) {
    $type = 'large';
    $key = array_search(0, $_SESSION['parkingLarge']) ?: null;
}
var_dump($type, $key);