【问题标题】:php multidimensional array loop issues in Laravel 5.7Laravel 5.7 中的 php 多维数组循环问题
【发布时间】:2019-01-09 07:53:25
【问题描述】:

我有一个购物车变量作为多维数组,如下所示

$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) 如果它不存在,则应将其添加为带有子的新父产品

我正在开发一个销售具有不同属性的产品的电子商务网站。例如,我有一部 iphone,其属性为 64gb、128gb,同时具有不同颜色的金色、黑色等。现在客户希望通过这种产品但每个变体的数量不同。比如说一个 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) { 返回假; } 别的 { 返回真; } } }

但只要满足第一个条件,foreach 循环就会停止。而实际上有一个子产品具有与要添加的产品属性匹配的属性。如何确保检查每个父产品的整个子产品?

【问题讨论】:

  • 它会停止,因为您返回 false 或 true。不要返回,只需根据需要增加一个变量并让循环继续。
  • @Chinelo 我更新的帖子解决了你的问题吗?
  • @DavidWinder 谢谢这正是我所做的。它解决了它感谢贡献

标签: php arrays multidimensional-array


【解决方案1】:

您的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 ]);
}

【讨论】:

  • 我尝试了您的方法,它有效。但同时它仍然将产品添加为孩子。即使在匹配之后。我不知道我是否正确地构造了 if else 语句。
  • @Chinelo 发生这种情况是因为如果您有 2 个具有相同 ID 但属性不同的产品-> 具有相同属性的产品被处理得很好,但是当 for 循环到达不同的产品时,它会添加他-我也会更新我的答案来解决这个问题
【解决方案2】:

$arraysAreEqual = ($a == $b); // 如果 $a 和 $b 具有相同的键/值对,则为 TRUE。 $arraysAreEqual = ($a === $b); // 如果 $a 和 $b 具有相同顺序和相同类型的相同键/值对,则为 TRUE。见:PHP - Check if two arrays are equal

伪代码:

// 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
   }
}

【讨论】:

  • 你好 Mgrahi 我尝试了 === 符号并且它有效,但条件语句的 else 部分仍然执行,尽管它找到了匹配的产品
猜你喜欢
  • 2012-04-06
  • 2018-07-30
  • 1970-01-01
  • 2013-06-25
  • 2019-07-17
  • 2012-05-13
  • 1970-01-01
  • 2012-11-21
  • 1970-01-01
相关资源
最近更新 更多