Пользовательский класс корзины в CodeIgniter показывает непредвиденное поведение

0

Я разрабатываю пользовательскую тележку в Code Igniter. Новые элементы добавляются без проблем. Но если я добавлю существующий элемент, вместо того, чтобы увеличивать количество товара в корзине, ничего не происходит вообще. Я просто не могу понять, где я пропустил это! Вот мой код:

Пояснить немного;

Предположим, я добавил в корзину пункт (name = Ray Ban, quanity = 2, price = 2), а затем снова добавил элемент (name = Ray Ban, quanity = 3, price = 20).

Я хочу, чтобы предмет в корзине был (name = Ray Ban, quantity = 5, price = 20).

Но этого не происходит. заранее спасибо

test.php

<?php class Test extends CI_Controller{


function __construct(){

    parent::__construct();

}


function index(){

    $this->load->library('Mycart');

    $item = array(

                     array(
                                        'item'      => 'Mango Fruity',
                                        'price'     => '30',
                                        'quantity'  =>  2

                        ),

                     array(
                                        'item'      => 'Mango Fruitym',
                                        'price'     => '300',
                                        'quantity'  =>  4

                        ),

                     array(
                                        'item'      => 'Mango Fruity',
                                        'price'     => '30',
                                        'quantity'  =>  3

                        )                           

        );

    $this->mycart->add_item($item);


}



} 

MyCart.php


<?php class Mycart {


public $cart_items;
public  $ci;

function __construct(){


    $this->ci           =   &get_instance();

    if($this->ci->session->userdata('cart'))

        $this->cart_items = $this->ci->session->userdata('cart');

    else

        $this->cart_items = array();


}


function add_item($items = 0){

    /* 
        Function Name      : add_item
        Function Author    : Manish Lamichhane
        Function Objective : Add items to cart

        Documentation:


        if(item is present in cart)

            quantity of the item in cart += quantity of item 

        for this it checks the item against all the items available in cart 

        if the item is present in cart,  occurrence flag is set

        after all the cart items are checked for this particular loop (inner forloop)

        once again the value of occurrence is checked

        if occurrence is set, that means the item was already in cart

        and thus the amount of this item is already increased in cart

   but if occurrence is set to 0, this means this particular item is not present in cart

        and thus this has to be added as new item in cart

    */


    if($item = 0){

        return;

    }elseif(is_array($items)){


    $item_already_in_cart = 0; //parameter to check if the added item is already in cart

        foreach($items as $item ){ 


            if(count($this->cart_items)){ //checks if cart is empty


                    foreach($this->cart_items as $cart_item){

                        if($cart_item['item'] == $item['item']){ 

                        /* if item to be added exists in cart,
                           add the quantity of the item in cart */

                        $cart_item['quantity'] += $item['quantity'];

                        $item_already_in_cart++; //flag sets if same item is encountered


                        }


                    }

/*  when control reaches here,
 it means first item to be added it check across all items in cart */

                    if($item_already_in_cart){ 

                        #checks if flag for this particular item is set
                        #if flag is set, it means the item was already in cart and thus quanitity was increased
                        #so the item need not be added in the cart

                        $item_already_in_cart = 0; 


                    }else{

                        #else if the $item_already_in_cart flag is not set, then add the item to cart

                        $this->cart_items[] = $item;

                    }

                }else{

                        $this->cart_items[] = $item; //if the cart was empty 



                }


        }

        echo "<pre>";print_r($this->cart_items);exit;   


    }else{

        return;

    }


}//add_item function ends here



}//class ends here
Теги:
codeigniter

2 ответа

0

Использование ссылки на переменную в цикле foreach сделало трюк !!!

foreach ($this-> cart_items as & $ cart_item) {

//код здесь

}

0

Я думаю, вы забыли добавить $this-> ci → session-> set_userdata ($this-> cart_items); Таким образом, вы не сохраняете корзину в сеансе. Попробуйте добавить

$this->ci->session->set_userdata($this->cart_items); 

до

echo "<pre>";print_r($this->cart_items);exit;   
  • 0
    спасибо за комментарий Роман. Но сессия здесь не имеет ничего общего. Если в корзине встречаются два одинаковых товара, она добавляет количество и не повторяет товары. Но этого не происходит. Я пытаюсь понять, почему.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню