【问题标题】:Seeking advice to optimize the following code chunk. (I need to avoid the IF ELSES)寻求建议以优化以下代码块。 (我需要避免 IF ELSE)
【发布时间】:2020-05-05 13:26:15
【问题描述】:

我有一个包含大约 30 个子部分的 JSON 文件。每个小节都会有所不同。我想把里面的数据转换成我想要的格式。代码工作正常。但我觉得它没有 100% 优化。

Client1Insurance, Client2Insurance, ClientFInsurance, FamilyInsurance, Client1Pension, Client2Pension, ClientFPension, FamilyPension

以上是这个 JSON 的外观示例。以上都是数组,里面有子数组。大约有 30 个这样的数组。

foreach ($json as $item) {
 if (strpos($crmMapKey, "Insurance")) {
     $returnArray[] = $this->handleInsurance($item);
 } elseif (strpos($crmMapKey, "Pension")) {
    $returnArray[] = $this->handlePension($item);
 } ... continues the comparison till the json ends
}

我需要一种方法来避免这么长的 if else 比较,这是我并不引以为豪的。有人能提出更好的方法吗?

谢谢。

【问题讨论】:

  • 这里不能使用开关。 Client1Insurance, Client2Insurance, ClientFInsurance, FamilyInsurance 将有 4 个案例。但是在我拥有的当前代码中,它将只有一个 strpos($crmMapKey, "Insurance") - 这避免了 4 种情况。 @AbraCadaver
  • switch(true) 那么情况就是你的strpos,所以也许不是最好的,但你可以使用它。
  • 还有其他选择吗? @AbraCadaver

标签: php optimization


【解决方案1】:

如果它们的名称与您在代码中显示的相同,则包含 Insurance 的内容将调用 handleInsurance 等。然后只需获取该术语并在方法调用中使用它:

preg_match('/Insurance|Pension/', $crmMapKey, $match);
$returnArray[] = $this->{'handle'.$match[0]}($item);

如果没有,那么您可以使用查找数组:

$lookup = ['Insurance' => 'doSomething', 'Pension' => 'doAnotherThing'];
preg_match('/Insurance|Pension/', $crmMapKey, $match);
$returnArray[] = $this->{'handle'.$lookup[$match[0]]}($item);

或者使用模式中的键,所以你只需要修改数组:

preg_match('/'.implode('|', array_keys($lookup)).'/', $crmMapKey, $match);

我在评论中提到的switch 可能不是最好的,但很有效:

switch(true) {
    case strpos($crmMapKey, "Insurance") !== false;
        $returnArray[] = $this->handleInsurance($item);
        break;

    case strpos($crmMapKey, "Pension") !== false;
        $returnArray[] = $this->handlePension($item);
        break;

    //etc...
}

【讨论】:

    【解决方案2】:

    另一种方法是调用基于变量的函数。

    foreach ($json as $item) {
        $returnArray[] = $crmMapKey($item);
    }
    
    function Client1Insurance($item) {
        // Do something in here.
        return $array;
    }
    
    function Client2Insurance($item) {
        // Do something in here.
        return $array;
    }
    

    我觉得做事的方式要优雅得多。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多