有条件在foreach循环内部过滤值并倒退



我有一个奇怪的问题,我无法绕过它。我尝试了多种方法来获得所需的结果,但没有成功。我正在寻找的是一组规则,例如在循环中满足条件的情况。因此,这是我到目前为止所做的,但尝试了多种不同的方式。即使定义了国家,邮政编码和运输方法,我也总是会得到一场比赛。几乎就像它忽略了这些价值。

如果有人可以将我指向正确的方向,我将感谢。

$country        = 'GB';
$postCode       = "LE5";
$shippingMethod = "subscription_shipping";
$shippingMatrix = array(
    array(
        "country"            => "GB",
        "isPostCodeExcluded" => "LE5",
        "shippingMethod"     => "subscription_shipping",
        "carrier"            => "Royal Mail",
        "carrierService"     => "Royal Mail",
    ),
    array(
        "country"            => "GB",
        "isPostCodeExcluded" => false,
        "shippingMethod"     => "subscription_shipping",
        "carrier"            => "DHL",
        "carrierService"     => "DHL",
    ),
    array(
        "country"            => false,
        "isPostCodeExcluded" => false,
        "shippingMethod"     => "subscription_shipping",
        "carrier"            => "Fallback",
        "carrierService"     => "Fallback",
    ),
    array(
        "country"            => "GB",
        "isPostCodeExcluded" => false,
        "shippingMethod"     => "standard_delivery",
        "carrier"            => "DPD",
        "carrierService"     => "DPD",
    ),
);
$carriers = [];
foreach ($shippingMatrix as $matrix) {
    // If only Shipping Method is matched then fall back will be the result
    if ($shippingMethod === $matrix['shippingMethod']) {
        $carriers = [
            $matrix['carrier'],
            $matrix['carrierService'],
        ];
        // If only Shipping Method & Country is matched then fall back will be the result DHL
        if ($country === $matrix['country']) {
            $carriers = [
                $matrix['carrier'],
                $matrix['carrierService'],
            ];
            // If only Shipping Method & Country & PostCode is matched then fall back will be the result Royal Mail
            if ($postCode === $matrix['isPostCodeExcluded']) {
                $carriers = [
                    $matrix['carrier'],
                    $matrix['carrierService'],
                ];
            }
        }
    }
}
var_dump($carriers);
态 值被覆盖。将 $ carriers 转换为 $ carriers [] 的所有需要做的一切。

这是下面的示例。

$carriers[]  = [
            $matrix['carrier'],
            $matrix['carrierService'],
          ];

感谢您的答复,但这不是必需的。经过一个很好的古老,认为我犯了新手的错误,将我的类型混合在一起。

$carriers = [];
foreach ($shippingMatrix as $matrix) {
    if ($shippingMethod === $matrix['shippingMethod'] && $country === $matrix['country']) {
        if ($postCode === $matrix['isPostCodeExcluded']) {
            $carriers = [
                $matrix['carrier'],
                $matrix['carrierService'],
            ];
        }
    }
    if ($shippingMethod === $matrix['shippingMethod'] && $country !== $matrix['country'] && !$country) {
        $carriers = [
            $matrix['carrier'],
            $matrix['carrierService'],
        ];
    }
}

最新更新