如何在此方法中排除0?

时间:2019-11-27 13:47:30

标签: php symfony

我有一个代码:

public function getMinPrice() {
        return array_reduce($this->getProduktLinks()->toArray(), function($lowest, $link) {
            return min($lowest ?? $link->getPrice(), $link->getPrice());
        });
    }

我想从其中排除price = 0处的记录。我该怎么做?

2 个答案:

答案 0 :(得分:0)

DragDropContext

答案 1 :(得分:0)

您可以在一行上完成此操作,但是您冒着无法阅读的风险,所以我建议您这样做:

public function getMinPrice() {
    return array_reduce($this->getProduktLinks()->toArray(), function($lowest, $link) {
        $min = min($lowest ?? $link->getPrice(), $link->getPrice());
        return $min ?: max($lowest ?? $link->getPrice(), $link->getPrice());
    });
}

逻辑很简单,如果最低为假(即0),它将返回另一个。但是,如果两者均为0,则可以根据需要添加其他逻辑。看起来像这样:

public function getMinPrice() {
    return array_reduce($this->getProduktLinks()->toArray(), function($lowest, $link) {
        $min = min($lowest ?? $link->getPrice(), $link->getPrice());
        return ($min ?: max($lowest ?? $link->getPrice(), $link->getPrice())) ?: "some other value";
    });
}