mercredi 30 juin 2021

Dynamic conditions inside foreach loop to create a new array by specific values

Is there a better way to shorten this code and create "dynamic" conditions on a loop to create a new array by specific values if an variable is not null ?

$data = $csv->data;
$result = [];

$advertiserId = null;
$country = 'DE';
$status = null;

foreach ($data as $item){
    if($advertiserId !== null && $country !== null && $status !== null) {
        if ($item['Membership Status'] === $status && $item['Primary Region'] === $country && $item['Advertiser ID'] === $advertiserId) {
            $result[] = $item;
        }
    }
    if($advertiserId !== null && $country !== null && $status === null) {
        if ($item['Primary Region'] === $country && $item['Advertiser ID'] === $advertiserId) {
            $result[] = $item;
        }
    }
    if($advertiserId !== null && $country === null && $status !== null) {
        if ($item['Membership Status'] === $status && $item['Advertiser ID'] === $advertiserId) {
            $result[] = $item;
        }
    }
    if($advertiserId === null && $country !== null && $status !== null) {
        if ($item['Membership Status'] === $status && $item['Primary Region'] === $country) {
            $result[] = $item;
        }
    }
}

Aucun commentaire:

Enregistrer un commentaire