jeudi 23 août 2018

Check if a collection contain another collection?

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



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire