dourou9477 2013-05-21 17:23
浏览 26
已采纳

删除会话数组中的项目

I've been wracking my brains for for three days and still can't find the solution to my problem of removing items from a session array.

I'm learning PHP and how to build a shopping cart; I know that there are frameworks but I really want to learn programming, solve problems and create things.

My problem is this: Say I placed three items in the cart...

  1. Cookies
  2. Donuts
  3. Cupcakes

When I delete an item in the shopping cart, everything else down the list (below that item) is deleted as well. If remove DONUTS, Cupcakes is removed as well. If I remove Cookies, the whole list is removed/cleared

But if I start from the bottom (Cookies) going up the list, it works fine; it will only remove the one I clicked.

Here's my code along with other attempts. Not styled yet, just working on logic.

 <?php

session_start();

$prodid = $_POST['prodid'];
$quantity = $_POST['quantity'];
$empty= $_POST['empty']; 
$removed = $_POST['remove'];

   if (isset($empty ))
    {
    unset($_SESSION['shop_cart']);
    }


if (!isset($_SESSION['shop_cart']))//Checking if Session is Set or empty
   {
      unset($_SESSION['shop_cart']);
      echo "Cart is empty";
   } else
   {
      if(count($_SESSION['shop_cart'])==NULL || count($_SESSION['shop_cart'])==0 )
      {
         echo "Cart is empty";
      }
   }



/////// THIS IS THE SECTION THAT I'VE BEEN FIDDLING WITH --Am I on the right track
    if (isset($removed))  
    {
    foreach ($_SESSION['shop_cart'] as $cart_line_item => $item)
       {
        if($prodid==$item['prodid'])
            {
            unset($_SESSION['shop_cart'][$cart_line_item]); ///9:47pm May 20, 2013 
            break;
            }   
        }
    }
///////////////////////////////////////////////////////////////////////////////////


//Check if item is already in cart 
foreach ($_SESSION['shop_cart'] as $cart_line_item => $item)
    {
    if ($item['prodid']==$prodid)
        {
        $quantity=0;
    echo "In Cart Already <br/>";
        break;           
        }
    }

$cap=count($_SESSION['shop_cart']);
$_SESSION['shop_cart'][$cap]['prodid']=$prodid;
$_SESSION['shop_cart'][$cap]['quantity']=$quantity;
$_SESSION['shop_cart'][$cap]['description']=$description;

//Prevent Items with zero quantity
foreach ($_SESSION['shop_cart'] as $cart_line_item => $item)
    {
    if ($item['quantity'] == 0 || $item['quantity'] == NULL)
        {
        unset($_SESSION['shop_cart'][$cart_line_item]);
        break;
        }
    }    


$total=0; //For Price

 if (isset($_SESSION['shop_cart']))  
  {
    for($i=0;$i<count($_SESSION['shop_cart']);$i++)
    {
        $prodid=$_SESSION['shop_cart'][$i]['prodid'];
        $quantity=$_SESSION['shop_cart'][$i]['quantity'];
        $description=$_SESSION['shop_cart'][$i]['description'];

        $query = "SELECT prodid, description, price FROM products WHERE prodid = $prodid";
        $result = mysqli_query($hook, $query);
        $row = mysqli_fetch_assoc($result);

        $prodid = $row['prodid'];
        $price = $row['price'];
        $description= $row['description'];

        $subtotal = $price * $quantity;
                    $total += $subtotal;

echo "$description($prodid)---Quantity: $quantity--- $$price";      

echo "<form action=\"$_SERVER[SCRIPT_NAME]\" method=\"post\" >";
echo "<INPUT TYPE=\"submit\" name=\"remove\" VALUE=\"Remove\">";
echo "<input type=\"hidden\" name=\"prodid\" value=$prodid />
";
echo "<input type=\"hidden\" name=\"counter\" value=\"$i\"/>
"; 
echo "</FORM>";

echo "--------------------------<br/><br/>";

    }                                                             
  }

echo "TOTAL $total <br/><br/>";

echo '<pre>'. var_dump( $_SESSION['shop_cart']).'<pre/>';

echo "<br/>";

echo "<form action=\"$_SERVER[SCRIPT_NAME]\" method=\"post\" >";
echo "<INPUT TYPE=\"submit\" name=\"empty\" VALUE=\"Empty Cart \">";
echo "</FORM>";

?> 

These versions of that section of code yield the same result

A.

$counter= $_POST['counter'];
echo "COUNTER $counter";

    if (isset($removed))
    {   
    unset($_SESSION['shop_cart'][$counter]);  
    continue;
    }

B.

if (isset($removed))
for($i=0;$i<count($_SESSION['shop_cart']);$i++)
    if($prodid==$_SESSION['shop_cart'][$i]['prodid'])
        {
         $_SESSION['shop_cart'][$i]=$quantity==0; 
          continue;
        }

C.

if (isset($removed))
for($i=0;$i<count($_SESSION['shop_cart']);$i++)
    if($prodid==$_SESSION['shop_cart'][$i]['prodid'])
      {
        unset($_SESSION['shop_cart'][$i]['prodid']); 
    //OR
        //unset($_SESSION['shop_cart'][$i]);  
        continue;
        }

This doesn't work at all

if (isset($removed))
{
foreach ($_SESSION['shop_cart'] as $cart_line_item => $item)
       {

        if($prodid==$item['prodid'])
            {
            unset($_SESSION['shop_cart']['prodid']);
            unset($_SESSION['shop_cart']['quantity']);
            unset($_SESSION['shop_cart']['description']);           
            continue;
            }    
}
}

For @Soyale:

Is this what you mean?:

if (isset($removed))  
{
foreach ($_SESSION['shop_cart'] as $cart_line_item => $item)
   {
    if($prodid==$item['prodid'])
        {
        unset($_SESSION['shop_cart'][$cart_line_item]);
        continue;
        }   
    }
}

Same result.

  • 写回答

1条回答 默认 最新

  • duanhuang3074 2013-05-21 20:27
    关注

    Your problem lies here:

        for($i=0;$i<count($_SESSION['shop_cart']);$i++)
        {
            $prodid=$_SESSION['shop_cart'][$i]['prodid'];
            $quantity=$_SESSION['shop_cart'][$i]['quantity'];
            $description=$_SESSION['shop_cart'][$i]['description'];
    
            $query = "SELECT prodid, description, price FROM products WHERE prodid = $prodid";
            $result = mysqli_query($hook, $query);
            $row = mysqli_fetch_assoc($result);
    
            $prodid = $row['prodid'];
            $price = $row['price'];
            $description= $row['description'];
    
            $subtotal = $price * $quantity;
                        $total += $subtotal;
    
    echo "$description($prodid)---Quantity: $quantity--- $$price";      
    
    echo "<form action=\"$_SERVER[SCRIPT_NAME]\" method=\"post\" >";
    echo "<INPUT TYPE=\"submit\" name=\"remove\" VALUE=\"Remove\">";
    echo "<input type=\"hidden\" name=\"prodid\" value=$prodid />
    ";
    echo "<input type=\"hidden\" name=\"counter\" value=\"$i\"/>
    "; 
    echo "</FORM>";
    
    echo "--------------------------<br/><br/>";
    
        }                                                             
      }
    

    You shuld use foreach instead for. Why? Because the keys were deleted when you use unset. Basic array i.e.

    array (size=2)
      0 => 
        array (size=3)
          'prodid' => string '1' (length=1)
          'quantity' => string '2' (length=1)
          'description' => null
      1 => 
        array (size=3)
          'prodid' => string '2' (length=1)
          'quantity' => string '2' (length=1)
          'description' => null
      2 => 
        array (size=3)
          'prodid' => string '3' (length=1)
          'quantity' => string '2' (length=1)
          'description' => null
    

    After deleting product with prodid=2 will look like this:

    array (size=2)
      0 => 
        array (size=3)
          'prodid' => string '1' (length=1)
          'quantity' => string '2' (length=1)
          'description' => null
      2 => 
        array (size=3)
          'prodid' => string '3' (length=1)
          'quantity' => string '2' (length=1)
          'description' => null
    

    Length of the final table is 2. When you use something like this for($i=0;$i<count($_SESSION['shop_cart']);$i++) then second product will newer be displayed (because keys). Even more there isn't row with index 1 so the empy row will be placed there.

    Look at this lines:

    $total=0; //For Price
    
     if (isset($_SESSION['shop_cart']))  
      {
        for($i=0;$i<count($_SESSION['shop_cart']);$i++) //-> this is a bad idea please change this to foreach
        {
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请问如何在openpcdet上对KITTI数据集的测试集进行结果评估?
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错