简体   繁体   English

PHP从多维数组中删除特定项目

[英]Php remove specific item from Multidimensional array Shopping cart

I have an array I am using for a shopping cart. 我有一个要用于购物车的数组。 I am trying to remove a specific item from the cart. 我正在尝试从购物车中移除特定物品。 I have tried using the key value of the array and unset() this does not work 100% for me. 我试过使用数组的键值和unset(),这对我来说不起作用100%。

Below is an example of my code. 以下是我的代码示例。 Cant figure out the best approach 不能找出最好的方法

<?php if (isset($_SESSION['cart'])!='') :?>   
<div class="col-md-6 well pull-right My-cart">
    <ol class = "Shopping-list">
        <form class = "Delete-from-cart" method = "POST">
            <?php $sum = 0; ?>
            <?php foreach ($_SESSION['cart'] as $Key => $row) : ?> 
            <li><?php echo $row['Title'] .' * '.$row['quantity']; ?> <i class="fas fa-trash-alt delete-icon"></i>
                <?php $total =    $sum+= $row['Price'] * $row['quantity']; ?>
                <input type="hidden" name="Deleted-ID" value="<?php echo $Key; ?>">
            </li>
            <?php endforeach; ?>
        </form>   
    </ol>
    <div class="col-sm-6 well pull-right Total">
        <?php echo 'Your total is '.$total; ?>
    </div>
</div>
<?php endif;?>

session_start();
$id = filter_var($_POST['Phone-ID'], FILTER_SANITIZE_NUMBER_INT);
$Phone_Title = filter_var($_POST['Phone-title'], FILTER_SANITIZE_STRING);
$Phone_Price = filter_var($_POST['Phone-price'], FILTER_SANITIZE_STRING);
$Phone_Quantity = filter_var($_POST['quantity'], FILTER_SANITIZE_NUMBER_INT);
$delete_phone = filter_var($_POST['Deleted-ID'], FILTER_SANITIZE_STRING);
$_SESSION['cart'][] = array(
     'Title' => $Phone_Title,
     'Price' => $Phone_Price,
     'quantity' => $Phone_Quantity
);
unset($_SESSION['cart'][$delete_phone]);
var_dump($_SESSION['cart']);

You are not assigning $id in the array 您没有在数组中分配$ id

<?php
    session_start();
    $id = filter_var($_POST['Phone-ID'], FILTER_SANITIZE_NUMBER_INT);
    $Phone_Title = filter_var($_POST['Phone-title'], FILTER_SANITIZE_STRING);
    $Phone_Price = filter_var($_POST['Phone-price'], FILTER_SANITIZE_STRING);
    $Phone_Quantity = filter_var($_POST['quantity'], FILTER_SANITIZE_NUMBER_INT);
    $delete_phone = filter_var($_POST['Deleted-ID'], FILTER_SANITIZE_STRING);

    $_SESSION['cart'][$id] = array(//Here you need to assign $id must be same as $delete_phone at the time of deletion
         'Title' => $Phone_Title,
         'Price' => $Phone_Price,
         'quantity' => $Phone_Quantity
    );
    unset($_SESSION['cart'][$delete_phone]);
    var_dump($_SESSION['cart']);
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM