dousu8767 2015-10-03 21:00
浏览 37
已采纳

替换/更新SESSION数组

This is kind of in conjunction to my first post, but new issue. I wasn't sure the protocol so I created a new topic. (link to first post)

I have searched around on here and found a couple different instances of my issue but cannot seem to understand anything enough to move forward with my own program.

Brief description: Shopping cart. I have a few items listed on a page with an itemID. The user clicks on an item, it gets added to the cart. If the user clicks the same item twice, the quantity should increment by one (currently hard coded). The $_SESSION['cart'] array should start empty and be dynamic.

Current issues: In testing it seems to only loop through the array once, array_push gives error even though parameter one is an array, does not remove an item as it should, and is not reading the quantity in the for loop. It displays '1' in print_r($_SESSION['cart'] but '0' in $_SESSION['cart']['itemID']['quantity'];

Warning: array_push() expects parameter 1 to be array, null given in C:\xampp\htdocs\A06_DictCart\controller\updateCart.php on line 25

Kind of a few different issues I suppose, but fixing one will help me move forward with the others, I would imagine they are semi-related.

viewCart.php

<?php
session_start();

/* Display the itemID and quantity of each item in the shopping cart.
This may be implemented by iterating though the items in the dictionary 
and displaying their keys and values. */
echo ' ** array/ '.print_r($_SESSION['cart']).' ** count/ '.count($_SESSION['cart']);
echo '<br>'.$_SESSION['cart']['itemID']['quantity'];
echo '<center><h2><u>SHOPPING CART</u></h2>';
echo '<br><TABLE border=1 cellPadding=3 cellSpacing=1>
        <TBODY>
        <TR>
          <TD>ItemID</TD>
          <TD>Quantity</TD>
          <TD>Remove from Cart</TD></TR>';

if (isset($_SESSION['cart'])) {
    $c = count($_SESSION['cart']);
    for ($x=0; $x <= $c; $x++){
        echo '<tr><td>'.$_SESSION['cart']['itemID'].'</td>';
        echo '<td>'.$_SESSION['cart']['itemID']['quantity'].'</td>';
        echo "<td><a href='updateCart.php?action=remove&amp;itemID=".$_SESSION['cart']['itemID']."&amp;quantity=".$qty."> Remove from Cart </a></td></tr>";
        $x++;
    }   
}
else {
    $msg = '<i> ** cart is empty ** </i>';
    echo '<tr> <td></td>';
    echo '<td> </td>';
    echo "<td> </td></tr>";
}

echo '</tbody></table>';
echo $msg;
echo '<br><br><a href="../controller/default.php">Back to Catalog</a>';
echo '<br><a href="../controller/updateCart.php?action=clear">Empty Cart</a></center>';
?>

updateCart.php

<?php
/* Read the values of action, itemID, and quantity from the querystring.  
Items will either be added or removed from the shopping cart depending 
on the values of the querystring. Once the quantity is 0 the item should 
be unset from the cart. */

session_start();

$action = $_GET['action'];
$itemID = $_GET['itemID'];
$qty = $_GET['quantity'];
$msg;

if (empty($_SESSION['cart'])) $_SESSION['cart'] = array();
//array(); //('123' => 0, '456' => 0, '789' => 0, '101' => 0);
//$cart = array($_SESSION['cart']);

// ADD TO CART
if ($action == 'add') { 
    if (!in_array($itemID, $_SESSION['cart'])) {    
        $_SESSION['cart']= array('itemID' => $itemID, 'quantity' => $qty);  // Insert new item
    } else {
        $temp = array($_SESSION['cart']);
        $q += $_SESSION['cart'][$itemID]['qty'];
        $temp = array('itemID' => $itemID, 'quantity' => $q);
        array_push($_SESSION['cart'][$itemID], $temp);// Update existing item's quantity
    }
    $msg = $qty.' of item # '.$itemID.' has been added to your cart.';
}
// REMOVE FROM CART
if ($action == 'remove'){ 
    if (($_SESSION['cart'][$itemID]['quantity'] - 1) <= 0)
        unset ($_SESSION['cart'][$itemID]); // If new value is zero, unset elements
    else
        $_SESSION['cart'][$itemID]['quantity']--;   // Else decrease quantity by one
    $msg = $qty.' of item # '.$itemID.' has been removed to your cart.';
}
// EMPTY CART
if ($action == 'clear') { 
    unset($_SESSION['cart']);   // Unset session
    session_destroy();  
    $msg = 'Your shopping cart has been emptied.';
}

?>


<HTML>
    <HEAD>
    </HEAD>
<BODY>
<center>
    <p> <?php echo $msg; ?><br><br>
    <p><a href="../controller/default.php">Back to Catalog</a></p>
    <p><a href="../controller/viewCart.php">View Cart</a></p>
</center>
</BODY>
</HTML>

Being that this is a work-in-progress there may be some discrepancies in the code syntax-wise that I have not discovered yet. Some of the code in the 'remove from cart' statement I saw in another post.

Any help is appreciated.

  • 写回答

2条回答 默认 最新

  • dpg78570 2015-10-03 21:27
    关注

    I did not test this, but try this code:

    // ADD TO CART
    if ($action == 'add') { 
        if (!isset($_SESSION['cart'][$itemID])) {    
            $_SESSION['cart'][$itemID] = array('itemID' => $itemID, 'quantity' => $qty);  // Insert new item
        } else {
            $_SESSION['cart'][$itemID]['quantity'] += $qty     
        }
        $msg = $qty.' of item # '.$itemID.' has been added to your cart.';
    }
    

    That is how I would write this. I suppose in your code

    $_SESSION['cart']= array('itemID' => $itemID, 'quantity' => $qty);  // Insert new item
    

    should be

    $_SESSION['cart'][$itemID] = array('itemID' => $itemID, 'quantity' => $qty);  // Insert new item
    

    And I think you mixed up 'qty' with your 'quantity' key in your original code. On update you read on the key qty but your initaliser had quantity as the key:

    $q += $_SESSION['cart'][$itemID]['qty'];
    

    might be supposed to be written as

    $q += $_SESSION['cart'][$itemID]['quantity'];
    

    EDIT: Note this Image

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 docker模式webrtc-streamer 无法播放公网rtsp
  • ¥15 学不会递归,理解不了汉诺塔参数变化
  • ¥15 基于图神经网络的COVID-19药物筛选研究
  • ¥30 软件自定义无线电该怎样使用
  • ¥15 R语言mediation包做中介分析,直接效应和间接效应都很小,为什么?
  • ¥15 Jenkins+k8s部署slave节点offline
  • ¥15 如何实现从tello无人机上获取实时传输的视频流,然后将获取的视频通过yolov5进行检测
  • ¥15 WPF使用Canvas绘制矢量图问题
  • ¥15 用三极管设计一个单管共射放大电路
  • ¥15 孟德尔随机化r语言运行问题