如何优化很多if循环?

时间:2017-01-02 18:03:47

标签: php

这种情况持续了12次:

    if (isset($this->month1)) {
        array_push($monthly, "Month 1: " . $this->month1)
    }

    if (isset($this->month2)) {
        array_push($monthly, "Month 2: " . $this->month2)
    }

    if (isset($this->month3)) {
        array_push($monthly, "Month 3: " . $this->month3)
    }

无论如何要优化这个?

1 个答案:

答案 0 :(得分:3)

您可以执行以下操作:

foreach (range(1, 12) as $i) {
    $param = 'month' . $i;
    if (isset($this->$param)) {
        array_push($monthly, "Month $i: " . $this->$param);
    }
}

希望这有帮助!