Корзина покупок php не может прекратить добавление одного и того же продукта в массив корзины

Это просто фото того результата, который у меня получился. Как видите, пункт 4 можно добавлять снова и снова. Что я хочу в своей корзине, так это то, что для каждого цвета элемент 4 можно добавить только один раз.

введите здесь описание изображения

if( isset($_SESSION['cart']) ){

    ################## Do looping to check array cart if already has item with same id and color ##########################

    $i = 0; 
    $j = 1; // set to index [1] //
    $found = '';

    foreach( $_SESSION['cart'] as $cart ){

        ######## Check if product chosen already exist in the cart #######

        if( $cart[$i]['id'] == $new_product['id'] && $cart[$i]['color'] == $new_product['color'] ){

            $found = true; // Found existing item in the array cart //

        }
        else{
            $found = false;
            $j++; // No item found in array cart, increase to index [2] //
        }

        ####### If no same item is found in cart, add the new product to the cart array ###############



        $i++; // Increase array index to check second array and so on //
    }

    if(!$found){ // No item found in array cart, add item into cart //

        $_SESSION['cart'][$j]['id'] = $new_product['id'];
        $_SESSION['cart'][$j]['product_name'] = $new_product['product_name'];
        $_SESSION['cart'][$j]['discount'] = $new_product['discount'];
        $_SESSION['cart'][$j]['qty'] = $new_product['qty'];
        $_SESSION['cart'][$j]['color'] = $new_product['color'];
        $_SESSION['cart'][$j]['shipping_fee'] = $new_product['shipping_fee'];

    }

}

else{

    $_SESSION['cart'][0]['id'] = $product['id'];
    $_SESSION['cart'][0]['product_name'] = $product['product_name'];
    $_SESSION['cart'][0]['discount'] = $product['discount'];
    $_SESSION['cart'][0]['qty'] = $qty;
    $_SESSION['cart'][0]['color'] = $color;
    $_SESSION['cart'][0]['shipping_fee'] = $shipping_fee;

}

Как я мог изменить свои коды?


person Jian Short    schedule 05.03.2014    source источник


Ответы (1)


попробуй это ...

if($found){ // item found in array cart

    $_SESSION['cart'][0]['id'] = $product['id'];
    $_SESSION['cart'][0]['product_name'] = $product['product_name'];
    $_SESSION['cart'][0]['discount'] = $product['discount'];
    $_SESSION['cart'][0]['qty'] = $qty;
    $_SESSION['cart'][0]['color'] = $color;
    $_SESSION['cart'][0]['shipping_fee'] = $shipping_fee;   

    }

}

else{ // no item found

     $_SESSION['cart'][$j]['id'] = $new_product['id'];
        $_SESSION['cart'][$j]['product_name'] = $new_product['product_name'];
        $_SESSION['cart'][$j]['discount'] = $new_product['discount'];
        $_SESSION['cart'][$j]['qty'] = $new_product['qty'];
        $_SESSION['cart'][$j]['color'] = $new_product['color'];
        $_SESSION['cart'][$j]['shipping_fee'] = $new_product['shipping_fee'];

}
person Teja Korlapati    schedule 05.03.2014