samedi 15 mai 2021

PHP - Issue with removing or modifying specific item in multidimensional array

I have a multidimensional array. The parent array includes items that each item inside is an array with its properties.

insertProduct.php checks everytime I add a new product to the array if the product already exists. If it doesn't it pushes it to the array, if it already exists it finds it and adds +1 to its quantity.

I am trying to create a functionality where pressing a button "Undo" removes the latest addition whether it was a whole product (which means its QTY would be 1 so it removes it altoghether) or if the latest addition was just a QTY increase (from 1 to 2) then remove 1 from the QTY.

However my issue is when I add a product that already exists but is not in the last spot of the array, the QTY does increase as it should be but then the UNDO does not do -1 to this item's QTY.

I don't know if it's alright to post a video but here's the pattern of the problem in a short gif

insertProduct.php

if (isset($_SESSION['myArray'])) {
    $inserted_products = $_SESSION['myArray'];
    $position = array_search($inserted_product_ean, array_column($inserted_products,0)); 

    //check if new product already exists
    if ($position !== false) {                                      
        $inserted_products[$position][2] = $inserted_products[$position][2] + 1;
        $latest_product = $inserted_products[$position];
        $_SESSION['latestProduct'] = $latest_product;
        $_SESSION['myArray'] = $inserted_products;

    } else {
        array_push($inserted_products, $product); //$product is an array of info about the item inserted
        $latest_product = $product;
        $_SESSION['latestProduct'] = $latest_product;
        $_SESSION['myArray'] = $inserted_products;
    }

} else {
    $latest_product = $product;
    $_SESSION['latestProduct'] = $latest_product;
    array_push($inserted_products, $product);
    $_SESSION['myArray'] = $inserted_products;
}

deleteLastEntry.php

<?php

if (isset($_SESSION['myArray'])) {
    $inserted_products = $_SESSION['myArray'];
    $inserted_products_length = count($inserted_products);
    if ($inserted_products_length > 0){
        $latest_product = $_SESSION['latestProduct'];
        $qty = $latest_product[2];
        if ($qty !== false && $qty > 1) {
            $qty = $qty - 1;        
            $latest_product[2] = $qty;
            array_pop($inserted_products);
            array_push($inserted_products, $latest_product);
            $_SESSION['myArray'] = $inserted_products;
        }else{
            array_pop($inserted_products);
            $_SESSION['myArray'] = $inserted_products;
        }
    }else{
        echo '<div class="error-msg">No products to remove</div>';
    }
}

?>

Aucun commentaire:

Enregistrer un commentaire