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

时间:2019-03-14 18:13:43

标签: laravel if-statement conditional-statements

我正在尝试创建一个条件来检查数组中的所有值是否均为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

什么是正确的方法?预先感谢!

2 个答案:

答案 0 :(得分:1)

尝试

def get(self, request, *args, **kwargs):
    self.object = self.get_object()
    context = self.get_context_data(object=self.object)
    return render(self.request,'mainapp/template_confirm_delete.html')
// 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';
});

答案 1 :(得分: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