简体   繁体   English

我可以基于数组做出if-else语句吗?

[英]Can I make a if-else statement based on a array?

Here is my current code: 这是我当前的代码:

if ( by == 'id') {
    handlePromises(identifier_websites)

} else if ( by == 'name'){
    handlePromises(names_websites)

} else if ( by == 'email' ) {
    handlePromises(email_websites)

} else if ( by == 'phone' ) {
    handlePromises(phone_websites)
}

Now I want to make it a little bit more modular (functional) . 现在,我想使其更具模块化(功能性) I mean, I want to make the whole code above based on an array like this: 我的意思是,我想基于这样的数组制作以上整个代码:

$parts = ['id', 'name', 'email', 'phone'];

So if I add one item to that array, then automatically a else if block should be added to the code based on that item . 因此,如果我将一个项目添加到该数组,则应将else if自动添加到基于该项目的代码中。

Is doing that possible? 有可能吗?

Not sure if I get you but here's how you can automate the above slightly. 不知道我是否能帮到您,但是您可以通过以下方法稍微自动地执行上述操作。

$parts = [ 
    'id' => identifier_websites, 
    'name' => names_websites, 
    'email' => emails_websites, 
    'phone' => phone_websites
];

foreach ($parts as $cond => $params) {
     if (by == $cond) { 
        handlePromises($params); 
        break; 
     }
}

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

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