创建一个条件来检查数组是否在Laravel中具有值

问题描述 投票:0回答:2

我试图创建一个条件来检查数组中的所有值是否为0.这是数组的示例。

array:4 [▼
  0 => "0"
  1 => "100"
  2 => "200"
  3 => "100"
]

这是我想要修复的条件

    //update the status of the order
    if(empty($input['remainingDeliveries'])) {
        $order_idAcceptedItem = $acceptItem['order_id'];
        $setStatus = \App\Orders::where('id', '=', $order_idAcceptedItem)->first();
        if ($setStatus)
        {
            $setStatus->status_id = 3;
        }      
        $setStatus->save();

携带阵列的$input['remainingDeliveries']

    } else {
        $order_idAcceptedItem = $acceptItem['order_id'];
        $setStatus = \App\Orders::where('id', '=', $order_idAcceptedItem)->first();
        if ($setStatus)
        {
            $setStatus->status_id = 4;
        }      
        $setStatus->save();
    }

起初,我认为我的条件还可以,但是当我尝试使用此数组值创建记录时,

array:4 [▼
  0 => "152"
  1 => "0"
  2 => "0"
  3 => "0"
]

它会触发ELSE

这样做的正确方法是什么?提前致谢!

laravel if-statement condition
2个回答
1
投票

尝试

// Filter. The $result array will be empty if all values equal "0".
$result = array_filter($inputArray, function($item) {
    // This should return a boolean value. True means discard, false means keep.
    return $item === '0';
});
if(!count($result)) {
  // all empty thus everything was "0".
}

1
投票

您可以尝试使用Laravel的Collection类来检查数组:

if( collect($input['remainingDeliveries'])->every(function($value, $key){
    return $value == '0';
}) ) {
    // they are all '0'
}

https://laravel.com/docs/5.8/collections#method-every

© www.soinside.com 2019 - 2024. All rights reserved.