簡體   English   中英

Laravel 5.7中的php多維數組循環問題

[英]php multidimensional array loop issues in Laravel 5.7

我有一個購物車變量作為多維數組,如下所示

$totalCart   =  {"17":[{"id":"17","name":"New! iPhone 6 64gb GSM Unlocked Smartphone Space Gray, Refurbished","quantity":"1","price":"5000","attributes":[{"Ram Size":"1gb 16gb"},{"Color":"Black"}]},
                       {"id":"17","name":"New! iPhone 6 64gb GSM Unlocked Smartphone Space Gray, Refurbished","quantity":"1","price":"5000","attributes":[{"Ram Size":" 4gb 64gb"},{"Color":" Gold"}]}]}

每當將商品添加到購物車時,它都會檢查商品ID是否存在於購物車變量中。

1)如果存在,它將檢查其子級是否具有與將要添加的產品的屬性相同的屬性。

a)如果屬性相同,則應增加數量或僅添加新價格。

b)否則它不具有相同的屬性,因此應將該產品添加為新的子項,但具有不同的屬性

2)如果不存在,則應將其作為帶有孩子的新父產品添加

我正在一個電子商務網站上銷售具有不同屬性的產品。 例如,我有一個具有諸如64GB,128GB等屬性的iPhone,同時還具有不同的顏色,例如金色,黑色。 現在,客戶希望通過這種產品,但每種變體的數量不同。 舉例來說,假設一個iPhone 64GB,數量為12的金色和同一iPhone 128GB,數量為5的黑色

現在這是我的實現:

public function addToCart(Request $request) {
    $productId = $request->productId;
    $productName = $request->productName;
    $productPrice = $request->productPrice;
    $qty = $request->qty;
    $productPhoto =  $request->productPhoto;
    $subTypes = [];

    if(isset($request->subtypes)) {
        foreach ($request->subtypes as $key => $value) {
            $result = $array = explode('_', $value);
            $subTypes[] = array($result[0] => $result[1]);
        }
    }
    $cart = session()->get('cart');


    // if cart is empty then this the first product
    if ($cart == null) {

        $cart[$productId][0] = [
            "id" => $productId,
            "name" => $productName,
            "quantity" => $qty,
            "price" => $productPrice,
            "photo" => $productPhoto,
            "attributes" => $subTypes
        ];
       /* $cart = [
            $productId[0] => [
                "id" => $productId,
                "name" => $productName,
                "quantity" => $qty,
                "price" => $productPrice,
                "photo" => $productPhoto,
                "attributes" => $subTypes
            ]
        ];*/
        session()->put('cart', $cart);
        return json_encode(['totalCart' => $cart]);
       return json_encode(['status' => 'ok','totalCart' => count($cart)]);

    }

    // if cart not empty then check if this product exist then increment quantity
   else if(isset($cart[$productId])) {

        foreach ($cart[$productId] as $key => $value2 ){
            if ($this->compareArray($value2['attributes'], $subTypes )){
                if ((int)$qty > 0) {
                    $cart[$productId][$key]['quantity'] = $cart[$productId][$key]['quantity'] + (int)$qty;
                }
                else{
                    $cart[$productId][$key]['price'] = $cart[$productId][$key]['price'] + (int)$productPrice;

                }
            }else{
                array_push($cart[$productId], [
                    "id" => $productId,
                    "name" => $productName,
                    "quantity" => $qty,
                    "price" => $productPrice,
                    "photo" => $productPhoto,
                    "attributes" => $subTypes
                ]
            );
            }
        }


       session()->put('cart', $cart);
       return json_encode(['totalCart' => $cart]);
       return json_encode(['status' => 'ok','totalCart' => count($cart)]);


    }else {

       // if item not exist in cart then add to cart
       $cart[$productId][0] = [
           "id" => $productId,
           "name" => $productName,
           "quantity" => $qty,
           "price" => $productPrice,
           "photo" => $productPhoto,
           "attributes" => $subTypes
       ];


       session()->put('cart', $cart);
       return json_encode(['totalCart' => $cart]);
       return json_encode(['status' => 'ok','totalCart' => count($cart)]);
    }
}

公共函數compareArray($ array1,$ array2){foreach($ array1 as $ key => $ value){if($ array2 [$ key]!= $ value){返回false; } else {返回true; }}}

但是foreach滿足第一個條件, foreach循環就會停止。 而實際上有一個子產品具有與要添加產品的屬性匹配的屬性。 如何確保檢查每個父產品的整個子級?

$ arraysAreEqual =($ a == $ b); //如果$ a和$ b具有相同的鍵/值對,則為TRUE。 $ arraysAreEqual =($ a === $ b); //如果$ a和$ b具有相同的鍵/值對且順序相同且類型相同,則為TRUE。 請參閱: PHP-檢查兩個數組是否相等

偽代碼:

// array_diff_key returns an array off different items compared to second parameter
if ($card === array_diff_key($totalCard,$card)) {
  // $card does not exist
  // toDo: add to $totalCard
} else {
   if($product === $totalCard[$productId]) {
     // raise quantity
   } else {
     // add as new child
   }
}

您的compareArray函數的邏輯錯誤。 目前,它將停止的是第一個屬性是相同的。

您需要更換

if ($this->compareArray($value2['attributes'], $subTypes )){

與:

if ($value2['attributes'] === $subTypes) {

已編輯

還要注意,您在所有產品上循環並檢查那里的屬性->如果至少一種產品具有不同的屬性,這將導致將該產品添加到列表中。 要解決此問題,請使用以下邏輯:

$found = false;
foreach ($cart[$productId] as $key => $value2 ) {
    if ($value2['attributes'] === $subTypes) {
        $found = true; // mark flag
        if ((int)$qty > 0) {
            $cart[$productId][$key]['quantity'] = $cart[$productId][$key]['quantity'] + (int)$qty;
        } else {
            $cart[$productId][$key]['price'] = $cart[$productId][$key]['price'] + (int)$productPrice;
        }
    }
}
if (!$found) { // if non prudect found add hi,
    array_push($cart[$productId], [ "id" => $productId, ... // add all field to new product ]);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM