繁体   English   中英

我怎样才能在 php 中更简洁地写这个 if-this-or-that

[英]how can I write this if-this-or-that more succinctly in php

我有一个 if 语句,其中包含许多 true 选项,我将其编写如下。 我怎样才能更简洁地写这个?

foreach($data_array as $person){
    if(
    isset($person['dept']) && $person['dept'] == $list && $person['status'] == 'Current' ||
    isset($person['dept2']) && $person['dept2'] == $list && $person['status'] == 'Current' ||
    isset($person['dept3']) && $person['dept3'] == $list && $person['status'] == 'Current' ||
    isset($person['dept4']) && $person['dept4'] == $list && $person['status'] == 'Current' ||
    isset($person['dept5']) && $person['dept5'] == $list && $person['status'] == 'Current'
    )
{ // do something

您可以编写 function 来缩短您的陈述:


function isValid(array $person, string $key, string $list): bool {
    return isset($person[$key]) && $person[$key] == $list;
}

foreach ($data_array as $person) {
    if (
        $person['status'] == 'Current'
        && (
            isValid($person, 'dept', $list)
            || isValid($person, 'dept2', $list)
            ...
        )
    )
}

如果您可以将$data_array格式化为以下格式:

[
    [
        'depts' => [
            'value1',
            'value2',
            ...
        ],
        'status' => 'Current'
    ],

    [
        'depts' => [
            'value3',
            'value4',
            ...
        ],
        'status' => 'Not Current'
    ]
]

那么您可以将代码大幅减少到 2 个条件:

foreach ($data_array as $person) {
    if ($person['status'] === 'Current' && in_array($list, $person['depts'])) {

    }
}

我实际上找到了足够简单的方法,不需要额外的功能或重新格式化我的数据:

foreach($data_array as $person) {
    for ($i=""; $i<=5; $i++){ // starts with "" because the first department does not have a #
        if(
        isset($person['dept'.$i]) &&
        $person['dept'.$i] == $dept['id'] &&
        $person['status'] == 'Current'
        ){
    // do stuff
    }
}
                    

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM