php-如果所有数组值都<=0,则执行

$result = Array ( 
[0] => Array ( [qty_received] => 1 ) 
[1] => Array ( [qty_received] => 12 ) 
[2] => Array ( [qty_received] => 1 ) 
[3] => Array ( [qty_received] => 0 ) 
[4] => Array ( [qty_received] => -1 ) 
)

qty_received数组的所有值小于或等于零(<=0)时,我试图运行更新查询,否则停止执行。

如果任何值 >0,我们可以停止执行。仅当 $result 中的所有值都 <=0 时才需要运行更新查询。

我尝试使用以下代码,但没有按预期工作。提前致谢。

foreach ($result as $qty_received) {
    if ($qty_received > 0){                
        break;
    }else{
        $this->db->update($this->table, $data);
    }
}

回答

我只是想到max,结合array_column:

// Find the highest value in the array, see if its lower than zero
$isFullyNegative = 0 >= max(array_column($array, 'qty_received'));

一种方法可能是 array_filter:

// take only the negatives, if the number of elements is the same as the
// the original one its fully negative 
$negatives = array_filter($array, function($value){ return $value <=0; });
$fullyNegative = count($array) === count($negatives);

您还可以创建一个轻量级的辅助函数,这可能更轻量级,因为它在找到正值时停止:

function isFullyNegative(array $values): bool {
    foreach($values as $value){
        if($value > 0 ){
            return false;
        }
    }
    return true;
}

当然,您也可以采用其他示例并利用它们来提高可用性


以上是php-如果所有数组值都&lt;=0,则执行的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>