D
D
devmo2017-03-01 18:39:41
PHP
devmo, 2017-03-01 18:39:41

How to calculate the quantity and display the amount (basket class + cookies)?

I recently switched to OOP and am making a shopping cart for the site. I found a basket here - Basket
I'm not very familiar with cookies yet and in general with OOP. But I want to understand.
There is a class Cart in which there are 2 methods responsible for products

public function getItems($for_sql = false)
{
    if ($for_sql) {
        return implode(',', $this->items);
    }

    return $this->items;
}

public function addItem($id)
{
    $id = (int)$id;

    $key = array_search($id, $this->items);

    if (!in_array($id, $this->items)) {
        array_push($this->items, $id);
    }
     Cookie::set('items', serialize($this->items));
}

And in the cart.php file, I display it in this way:
echo "My cart: <br>";
foreach ($items as $items) {
    echo "<b>{$items['name']}</b> | Количество " .count($items['id']). " | <a href='cart.php?action=delete&id={$items['id']}'>Удалить из корзины</a><br>";

I tried to display the number of repeated id through count, but also without success. Therefore, I ask for help How to do the following:
  • How to add up the quantity of an item if that item has already been added to the cart? At the moment, only 1 time the product is added, and then the quantity of this product is not added (+ 1 to the quantity)
  • How to display the total amount using this cart class?

I tried to add the array_key_exists() function to the addItem($id) method, but without success. The quantity does not add up.
UPD. result for webinar - prntscr.com/eeq1jc

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Timofeev, 2017-03-01
@webinar

Why ajax, cookies, etc.? Extra requests to the server, the problem of disabled cookies. Maybe it's better to use localStorage?
https://www.w3schools.com/html/html5_webstorage.asp
Everything is client side, the server smiles.
Now according to your code:
count($items['id'])- I doubt very much that there is any sense in this. In any case, to help you need to see the architecture of the array. Do <pre><?php print_r($items)?></pre>and add the result to the question.

F
FanatPHP, 2017-03-01
@FanatPHP

In short, the author of this "basket" is an idiot.
Nobody makes baskets like that.
Run from this site wherever your eyes look. This "devionity" is even worse than Popov's video courses.
The basket should contain only unique products, and the quantity is written in a separate field.

if (isset($this->products[$id])) {
    $this->products[$id] = 1;
} else 
    $this->products[$id]++;
}

more or less like this.
but in order to do it humanly, it will be necessary to throw out all the idiotic code that you are sold on this site.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question