Laravel:如何检查数组是否为空?

时间:2019-08-08 15:22:50

标签: laravel eloquent laravel-query-builder

假设我有此查询:

std::future

它返回的数据是空的,像这样: $schedules = [33,34]; foreach ($schedules as $schedule) { $buses[] = DB::table("buses")->select('id', 'bus_number') ->where('station_id', $stations_id) ->whereNotNull('Driver_id') ->get(); }

所以,我的问题是如何检查其中是否有数据?

2 个答案:

答案 0 :(得分:0)

一个简单的解决方案是排除空填充值:

$schedules = [33,34];
foreach ($schedules as $schedule) {
     $bus = DB::table("buses")->select('id', 'bus_number')
                  ->where('station_id', $stations_id)
                  ->whereNotNull('Driver_id')
                  ->get();
     if($bus && isset($bus->id)) {
         $buses[] = $bus;
     }
 }
 if($buses && count($buses)>0) {
     //has value
 }

如果您将Schedule与公交车相关联,则可以使用类似这样的内容;

$schedules = Schedule::whereIn('id',$schedule_ids)->with('buses')->get();
//and you dont need to set into an array

答案 1 :(得分:0)

您可以使用count()函数,如下所示:

$schedules = [33,34];
foreach ($schedules as $schedule) {
   $bus = DB::table("buses")->select('id', 'bus_number')
              ->where('station_id', $stations_id)
              ->whereNotNull('Driver_id')
              ->get();

   if(count($buses) > 0) {
      $buses[] = $bus;
   }
}