Using Laravel Collection, what the good way to check if check if a collection ($selectedItems) contain another collection ($orders)?
I am currently using two foreach loop $selectedItems and check if it exist in the $orders using another loop.
$selectedItems = collect([
["ItemId" => "T123", "Price" => "12.00"],
["ItemId" => "T99", "Price" => "13.00"],
]);
$orders = collect([
["ItemId" => "T123", "Cost" => "12.00"],
["ItemId" => "T99", "Cost" => "13.00"],
["ItemId" => "T33", "Cost" => "13.00"],
]);
$found = [];
foreach ($selectedItems as $selectedItem)
{
foreach($orders as $orderItem)
{
if ($orderItem['ItemId'] !== $selectedItem['ItemId']) {
continue;
}
$found[] = $orderItem;
}
}
if (count($found) == $selectedItems->count()) {
dd("Matched");
} else {
dd("Not Matched");
}
How to also ensure the Price from $selectedItems is the same as Cost in the $orders
$selectedItems->diff($orders)->isEmpty();
This will diff the second collection from the first and if the result is empty you can be sure that all your items exist in the other collection.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With