如何在php会话数组中添加第三个值?

时间:2016-08-26 11:34:04

标签: php

我正在开发一款我正在尝试为项目构建的购物车,但却收到了一些php错误消息;我试图对自己进行排序同样的错误继续发生。购物车背后的想法是:

  • 此人从下拉列表中选择鞋码

- 如果商品ID不在购物车中,那么它就是新产品......所以它被添加到购物车

- 如果id和大小相同,那么我们会增加与该id相关的数量。

<?php
  $items = array(
  array('id' => '1', 'desc' => 'Addidas Original FlipFlap','price' => 24.95, 'size'=>'424546'),
  array('id' => '2', 'desc' => 'Reebok Filas','price' => 200, 'size'=>'323845'),
  array('id' => '3', 'desc' => 'Songs of the Goldfish (2CD set)','price' => 19.99),
  array('id' => '4', 'desc' => 'Simply JavaScript (SitePoint)', 'price' => 39.95)
  );

session_start();
 if (!isset($_SESSION['cart'])) {
 $_SESSION['cart'] = array();
 }

if (isset($_POST['action']) and $_POST['action'] == 'Buy')  {
 $size="";
 //Get the values for the post and make sure they are integers
 $pid = filter_var( $_POST['id'], FILTER_VALIDATE_INT, array('min_range'=> 1) );
 $size = $_POST['doSize'];
 if (isset($_SESSION['cart'][$pid], $size)) {
    $_SESSION['cart'][$pid][$size]['quantity']++;
print_r($_SESSION['cart']);
 }

else{
$_SESSION['cart'][$pid][$size]= array('id'=>$pid, 'size'=>$size, 'quantity'=>1);
print_r($_SESSION['cart']);
   }
 }//END POST 
include'catalog.html.php';

 //unset($_SESSION['cart']);
 ?>

HERE MY HTML

<!DOCTYPE html>
  <head>
  <title>Product catalog</title>
  <meta http-equiv="content-type"
  content="text/html; charset=utf-8" />
  <style type="text/css">
 table {
 border-collapse: collapse;
 }
 td, th {
 border: 1px solid black;
 }
 </style>
 </head>
<body>
 <p>Your cart contains <?php echo count($_SESSION['cart']);?> item(s).</p>
 <p><a href="?cart">View your cart</a></p>
 <table border="1">
 <thead>
 <tr>
 <th>Item Description</th>
 <th>Price</th>
 <th>Size</th>
 </tr>
 </thead>

 <tbody>
 <?php foreach ($items as $item): ?>
 <tr>
 <td><?php echo $item['desc']; ?></td>
 <td>
 $<?php echo number_format($item['price'], 2); ?>
 </td>
 <td>

<form action="" method="post">

 <?php if (isset($item['size'])) { ?>

 <select name="doSize">
 <?php foreach(str_split($item['size'], 2) as $size):?>
 <option value="<?php echo $size;?>"><?php echo $size;?></option>
 <?php endforeach;?>


 </select>
 <?php }?>
  </td>

 <td>
 <div>
 <input type="hidden" name="id" value="<?php echo $item['id']; ?>"/>
 <input type="submit" name="action" value="Buy"/>
 </div>
 </form>
 </td>
 </tr>
 <?php endforeach; ?>
 </tbody>
 </table>
 <p>All prices are in imaginary dollars.</p>
 </body> 
 </html>

当我添加新产品时,一切正常。数量增加和所有......但是当项目最多添加3项时,我得到的错误

Notice: Undefined offset: 38 in C:\wamp\www\shopping-cart\index.php on line 22

Notice: Undefined index: quantity in C:\wamp\www\shopping-cart\index.php on line 22.

我试图将自己排除在外但状态相同。 有人可以帮我找到问题并告诉你如何理清吗?

0 个答案:

没有答案