【问题标题】:Php remove specific item from Multidimensional array Shopping cartphp从多维数组购物车中删除特定项目
【发布时间】:2018-05-10 16:35:20
【问题描述】:

我有一个用于购物车的数组。我正在尝试从购物车中删除特定商品。我已经尝试使用数组的键值和 unset() 这对我来说不是 100% 的。

以下是我的代码示例。想不出最好的方法

<?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']);

【问题讨论】:

  • 您的$_POST['Deleted-ID'] 是否与$_SESSION['cart'] 的位置实际匹配?
  • 我已经在我的用户端添加了表单
  • 您是否尝试将会话购物车分配给新变量,取消设置它的内容,然后重新分配给会话购物车新的修改值?
  • 你可以试试$_SESSION['cart'][$delete_phone] = array();吗?
  • $delete_phone 里有什么?

标签: php


【解决方案1】:

您没有在数组中分配 $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']);
?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-19
    • 2023-01-27
    相关资源
    最近更新 更多