Heim  >  Fragen und Antworten  >  Hauptteil

Laravel 9-Array-Filterung

Ich habe dieses Array „cart_items“ und es funktioniert einwandfrei, wenn es dem Datenbankspeicher zugeordnet wird (wie im Code gezeigt).

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

Ich muss ein Array mit Arr:where() filtern, wobei „product shop_id“ ein bestimmter Wert ist.

Ich habe versucht, die if-Funktion zu verwenden, aber der Code führt nur eine Schleife aus und gibt true zurück, wenn shop_id vorhanden ist.

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

Ich muss das Array der Produkt-Shop_ID auf einen bestimmten Wert filtern.

P粉604848588P粉604848588261 Tage vor337

Antworte allen(1)Ich werde antworten

  • P粉512729862

    P粉5127298622024-01-07 12:01:58

    我知道这个解决方案并不可取。那就太简单了。您想使用 Laravel 9 组件来做到这一点。无论如何我都会告诉你:

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

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

    Antwort
    0
  • StornierenAntwort