I have this array cart_items and works fine when mapped for database storage as in the code.
$cart_items = [ {"id":8, "cart_id":7, "product_id":4, "variation_id":null, "quantity":1, "price":30, "tax":0, "attrs":null, "gross_total":30, "net_total":30, "tax_total":0, "product":{ "id":4, "parent_id":null, "category_id":1, "shop_id":1, "title":"Ladies Blazer", "unit":"item", "sale_price":30, "general_price":35 } }, { "id":9, "cart_id":7, "product_id":1, "variation_id":null, "quantity":2, "price":11, "tax":0, "attrs":null, "gross_total":22, "net_total":22, "tax_total":0, "product":{ "id":1, "parent_id":null, "category_id":2, "shop_id":2, "title":"Sport Bottles", "unit":"item", "sale_price":11, "general_price":9 } } ]
$line_item_params = $cart_items->map(function (CartItem $item) { $p = [ 'product_id' => $item->product_id, //add filtered shop_id here 'variation_id' => $item->variation_id, 'product_title' => $item->product->title, 'quantity' => $item->quantity, 'price' => $item->price, 'tax' => $item->tax, 'attrs' => $item->attrs, ]; return $p; })->toArray();
I need to filter the array using Arr:where(), where the product shop_id is a specific value.
I tried using an if function but the code just looped returing true where the shop_id was present.
$line_item_params = $cart_items->map(function (CartItem $item) { if ($item->product['shop_id'] == 1){ $p = [ 'product_id' => $item->product_id, //add filtered shop_id here //'shop_id' => $shop->id, 'variation_id' => $item->variation_id, 'product_title' => $item->product->title, 'quantity' => $item->quantity, 'price' => $item->price, 'tax' => $item->tax, 'attrs' => $item->attrs, ]; } return $p; })->toArray();
I need to filter the array where the product shop_id is a specific value.
Advertisement
Answer
I know that this solution is not desirable. It would be too simplistic. You want to do it with Laravel 9 components. I’ll show you anyway:
$shop_id = 1; $result = array_filter($arr, fn($v) => $v["product"]["shop_id"] == $shop_id);
Complete example: https://3v4l.org/19gnD