Php 在Laravel中返回更多结果时,通过关联数组循环返回单个结果
我有一个返回关联数组的查询。我所知道的是,当我尝试使用if语句检查一个日期是否等于另一个日期时,我只得到了只针对第一个值运行的条件,即Php 在Laravel中返回更多结果时,通过关联数组循环返回单个结果,php,mysql,arrays,laravel,Php,Mysql,Arrays,Laravel,我有一个返回关联数组的查询。我所知道的是,当我尝试使用if语句检查一个日期是否等于另一个日期时,我只得到了只针对第一个值运行的条件,即2017-09-21 以下是查询: $startDates = Academic::all()->pluck('date_start'); 查询结果: Collection {#299 #items: array:2 [ 0 => Carbon {#298 +"date": "2017-09-21 00:00:00.00000
2017-09-21
以下是查询:
$startDates = Academic::all()->pluck('date_start');
查询结果:
Collection {#299
#items: array:2 [
0 => Carbon {#298
+"date": "2017-09-21 00:00:00.000000"
+"timezone_type": 3
+"timezone": "UTC"
}
1 => Carbon {#304
+"date": "2018-06-07 00:00:00.000000"
+"timezone_type": 3
+"timezone": "UTC"
}
]
}
我的循环和if语句:
$recieveDate = Carbon::createFromDate($date); // assume value is 2017
foreach ($startDates as $key => $value) {
// this only check against 2017 and not 2018
if ($value->year == $recieveDate->year) {
return response()->json(['exists' => 'The year of School Date Start already exists']);
} else {
return response()->json(['none' => null]);
}
}
如何让它检查
$receivedate
是否等于集合数组中的第二个值,即2018-06-07
?循环所有条目,如果得到匹配,则将该值更改为true
$recieveDate = Carbon::createFromDate($date); // assume value is 2017
$found = false;
foreach ($startDates as $key => $value) {
if ($value->year == $recieveDate->year) {
$found = true;
break; //stop loop so you don't have to iterate more.
}
}
if($found) {
return response()->json(['exists' => 'The year of School Date Start already exists']);
} else {
return response()->json(['none' => null]);
}
由于$startDates
是一个集合,您可以使用其中一个来查找元素:
$recieveDate = Carbon::createFromDate($date);
$found = $collection->search(function ($item, $key) use ($recieveDate) {
return $item->year == $recieveDate->year;
});
if($found) {
return response()->json(['exists' => 'The year of School Date Start already exists']);
} else {
return response()->json(['none' => null]);
}
循环所有条目,如果得到匹配项,则将值更改为true
$recieveDate = Carbon::createFromDate($date); // assume value is 2017
$found = false;
foreach ($startDates as $key => $value) {
if ($value->year == $recieveDate->year) {
$found = true;
break; //stop loop so you don't have to iterate more.
}
}
if($found) {
return response()->json(['exists' => 'The year of School Date Start already exists']);
} else {
return response()->json(['none' => null]);
}
由于$startDates
是一个集合,您可以使用其中一个来查找元素:
$recieveDate = Carbon::createFromDate($date);
$found = $collection->search(function ($item, $key) use ($recieveDate) {
return $item->year == $recieveDate->year;
});
if($found) {
return response()->json(['exists' => 'The year of School Date Start already exists']);
} else {
return response()->json(['none' => null]);
}
很抱歉我反应晚了。两者都很好,但你认为哪一个最快?我认为第一个解决方案的算法与第二个解决方案相同,因此我建议使用第二个解决方案,因为它看起来更干净,并且再次使用了LaravelThanks的全部功能。朋友,很抱歉反应太晚。两者都很好,但你认为哪一个最快?我认为第一个解决方案的算法与第二个相同,因此我建议使用第二个,因为它看起来更干净,并且再次使用了LaravelThanks的全部功能。