unset数组值和会话中的键

时间:2015-11-21 12:59:53

标签: php arrays session

我差不多完成了购物车,但我不知道如何从购物车中删除商品。我正在使用存储在会话中的数组。所以我想取消设置数组中的选定项目(使用我添加的复选框)。

products.php

cat<a href ="Adding-to-cart.php?id=2222"> add to cart<a/><br>
dog<a href ="Adding-to-cart?id=1111"> add to cart<a/><br>
bird<a href ="Adding-to-cart?id=5555"> add to cart<a/><br>

添加到购物车

code 
    <?php 
session_start();
if(empty($_SESSION['animals']))
    {
    $_SESSION['animals'] = array();
    }

$_SESSION['animals']["".$_GET['id'].""] = 1;


?>

cart.php

<?php
//////////////////////////////////////////////
$con = mysql_connect("localhost","root","");
mysql_select_db("items",$con);
//////////////////////////////////////////////
session_start();

// create an array
$my_array=array();


// put the array in a session variable
if(!isset($_SESSION['animals']))
    $_SESSION['animals']=$my_array;

// move submit code outside of foreach loop
if (isset($_POST["submit"])) 
{
for ($i = 0; $i < count($_POST['aaa']); $i++) {
    $aaa = $_POST['aaa'][$i];
    $key_var = $_POST['ke'][$i];

    // setting the session spesific session array value different for each key  
    $_SESSION['animals'][$key_var] = $aaa;
}

////removing checked item from shopping cart    
if (isset($_POST['brosrs'])) {

/////////////Things that I have tried/////////////
////unset($_SESSION['animals'][$key_var]);///////

//unset($_SESSION['animals'][$to_unset]); 

} 
////removing checked item from shopping cart/////
////////////////////////////////////////////////
}
?>

<table >
<tr >
<td ><b>ID</b></td>
<td ><b>Name</b></td>       
<td ><b>Price</b></td>
<td ><b>Subtotal</b></td>
<td ><b>Product ID is</b></td>
<td ><b>Quantity</b></td>
</tr>

<form method="post" action="">
<?php
//// declate the total price and start it as 0 coz its before the actual items added to cart
$total_price=0;
$subtotal = 0;
// loop through the session array with foreach
foreach($_SESSION['animals'] as $key=>$value)
{   

////////////////////////////DUMPING EVERYTHING FROM DATABASE////////////////////////////////////////////////

    $key_array = array_keys($_SESSION['animals']);

// Get record where $key exists.
$sql = "SELECT id, name, price FROM products WHERE id IN ({$key}) ORDER BY name";
$myData =  mysql_query($sql,$con);

// Loop through each record and see if $key_array is present in $row['id'] db
while($row = mysql_fetch_array($myData)){
if(in_array($row['id'], $key_array)){
    // display records 

    echo "<tr>";
    echo "<td >".  $row['id']. "</td>";
    echo "<td class='name'>".$row['name']. "</td>";
    echo "<td class='qtyid'>". $row['price']. "</td>";
    echo "<br/>";   
    $quantity_calc = $value;
    $subtotal = $value * $row['price']; 
    $price = $row['price'];

    echo "<td>" . $subtotal . "</td>";  
            }
            $total_price += $subtotal;

}  

////////////////////////////DUMPING EVERYTHING FROM DATABASE////////////////////////////////////////////////

    // and print out the values quantity

   echo " <td> Product ID is " .$key. " Quantity is  </td>";

    // getting the updated value from input box
    ?> 
        <!-- <td ><input type="text" name="aaa[]" value="<?php echo $value ; ?>" size="2" /></td> -->
        <td>  <input id="numberinputsize" type="number"  size="1" name="aaa[]" min="1" max="10" value="<?php echo $value ; ?>" > </td>
        <!-- take a hidden input with value of key -->
        <td ><input type="hidden" name="ke[]" value="<?php echo $key; ?>"><br></td>

        <!------------------------adding a remove item checkbox ------------------------------>
        <!------------------------adding a remove item checkbox ------------------------------>
        <td> <input type ="checkbox" name="brosrs" value = "<?php echo $key; ?>"><?php echo $key; ?></input> </td>
        <!------------------------adding a remove item checkbox ------------------------------>
        <!------------------------adding a remove item checkbox ------------------------------>
    <?php

 echo "</tr>";

}

?>

<tr>
<td>Total amount $<?php Echo $total_price; ?></td>
<td><a href="products-legit.php">back to shopping</a></td>
<td> <input class="inputbox" type="submit" value="Update value of key" name="submit"/></td> 
</tr>
</table>
</form>

<style>
table { 
width:1000px; 
}
</style>

谢谢!

更新<!/强> 对不起,但为了清楚说明伙伴们,我有一个产品页面,我将数据库中的id添加为存储在会话中的密钥。单击添加到购物车后,用户将被重定向到Adding-to-cart.php页面,其中数组将插入到会话中。然后,当你去购物车时,你可以看到物品。问题是&gt;&gt;&gt;当我在购物车中有2件或更多物品,并删除第一件商品时,购物车中的最后一件商品将被删除。

2 个答案:

答案 0 :(得分:0)

这是演示如何有想法以你的方式改变实现

cart.php

<?php 

ob_start();
session_start();
$_SESSION['data']=array('Cat','dog','bird');
//echo "<pre>"; print_r($_SESSION['data']);exit;
?>
<html>
<head>
<script src="jquery.js"></script>
<script>
$(document).ready(function(){
    $("#remove").on('click',function(){
        var toRemove=$('#toRemove').val();
        $.ajax('goToRemove.php',{
            data:{"toRemove":toRemove}
        });


    });
});
</script>
</head>
<body>
<form name="add" id="frmAdd" method="post" action="add.php?action=add" enctype="multipart/form-data">
<input type="text" name="toRemove" value="" id="toRemove"/>
<input type="button" name="add" id="remove" value="ADD">
</form>

</body>
</html>

goToRemove.php

<?php 
ob_start();
session_start();
echo "<pre>"; print_r($_SESSION['data']);
$to_delete=array_search($_REQUEST['toRemove'], $_SESSION['data']); 
unset($_SESSION['data'][$to_delete]);
echo "<pre>";print_r($_SESSION);
?>

答案 1 :(得分:0)

我假设您的购物车是多维数组,因为您没有提供数据示例。从购物车中查找和删除商品的简便方法是将array_search()array_column();合并

$cart = array(
  array('id'=>1,'name'=>'Awesome sauce'),
  array('id'=>2,'name'=>'Not so awesome sauce'),
  array('id'=>3,'name'=>'Really awesome sauce'),
);

//search $cart array for the value of 2 in the id key of the array and unset it.
unset($cart[array_search(2, array_column($cart, 'id'))]);

print_r($cart);

/* 
OUTPUT:

Array ( [0] => Array ( [id] => 1 [name] => Awesome sauce ) [2] => Array ( [id] => 3 [name] => Really awesome sauce ) )

*/

/*******Indexed array****************/
$cart = array( '2222' => 1 ,'1111' => 1 ,'6666' => 1 ,'5555' => 1 );
unset($cart['2222']);
print_r($cart);

/*
OUTPUT:
Array ( [1111] => 1 [6666] => 1 [5555] => 1 )
*/