У меня есть коллекция, содержащая два массива:
array:2 [
0 => array:3 [
"cde" => "cd542"
"startDate" => "2022-10-27"
"endDate" => null
]
1 => array:3 [
"cde" => "cd547"
"startDate" => "2022-10-27"
"endDate" => null
]
]
я попробовал метод ->contains, но он не работает
Это кажется странным вариантом использования, но это должно привести вас к правильному пути:
$sameElements = [
[
"Code" => "AKAR02",
"startDate" => "2022-10-27",
"endDate" => null,
],
[
"Code" => "AKAR02",
"startDate" => "2022-10-27",
"endDate" => null,
]
];
$collection = collect($sameElements);
[$first, $second] = $collection->only(0, 1);
if (
$first['code'] === $second['code']
&& $first['startDate'] === $second['endDate']
) {
// take the first element if they have the same code & the same start date
} else {
// do something else?
}
//if they have different startDate take the most recent one
$diffElements = [
[
"Code" => "AKAR02",
"startDate" => "2022-10-27",
"endDate" => null,
],
[
"Code" => "AKAR02",
"startDate" => "2022-10-01",
"endDate" => null,
]
];
$collection = collect($diffElements);
[$first, $second] = $collection->only(0, 1);
// if they have different startDate take the most recent one
if ($first['startDate'] != $second['startDate']) {
// do something with the most recent one
$mostRecent = $collection->sort(function ($a, $b) {
return strtotime($a['startDate']) <=> strtotime($b['startDate']);
})->first();
} else {
// do something else
}
При сравнении строк даты в формате Y-m-d нет необходимости вызывать
strtotime()
. Эти значения будут правильно сравниваться как простые строки. «Последние» должны быть$b <=> $a
(в порядке убывания). Ваш ответ сравнивает$a <=> $b
(в порядке возрастания).