Laravel 9 數組過濾
P粉604848588
P粉604848588 2024-01-06 15:56:43
0
1
410

我有這個陣列 cart_items,並且在映射到資料庫儲存(如程式碼中所示)時工作正常。

$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();

我需要使用 Arr:where() 過濾數組,其中產品 shop_id 是特定值。

我嘗試使用 if 函數,但程式碼只是循環返回 true,其中存在 shop_id。

$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();

我需要過濾產品shop_id為特定值的陣列。

P粉604848588
P粉604848588

全部回覆(1)
P粉512729862

我知道這個解決方案並不可取。那就太簡單了。您想使用 Laravel 9 元件來做到這一點。無論如何我都會告訴你:

$shop_id = 1;
$result = array_filter($arr, fn($v) => $v["product"]["shop_id"] == $shop_id);

完整範例:https://3v4l.org/19gnD

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板