mercredi 7 février 2018

Conditional Inside A Foreach Loop To Filter Value And Have A Fall Back

I have a strange problem and I can't get my head around it. I have tried loads of different ways to get the desired result but with no success. What I am looking for is a set of rules like fall backs if conditions are met in a loop. So this is what I have done so far but have tried multitude of different ways. If someone can point me to the right direction I would be grateful thanks.

$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);

Aucun commentaire:

Enregistrer un commentaire