Php会话购物车阵列循环的输入

时间:2018-02-19 11:36:13

标签: php html

我有一个购物车我有一个带有类名的输入数组。我试图将数据发布到会话数组并打印出数组的结果。我有这个工作正常。问题是我似乎只能让它将当前选定的项返回到数组中并返回数组。下一个选定的项目将替换最后一个项目。

<?php session_start();?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">


//This will echo out the sessions in the array but instead it only ever displays one. 
  <?php 

echo "Number of Items in the cart = ".sizeof($_SESSION['cart'])." <a href=cart-remove-all.php>Remove all</a><br>";

while (list ($key, $val) = each ($_SESSION['cart'])) { 
echo "$key -> $val <br>"; 
}
    ?>

<?php 

$myarray = array('Test phone 1','Test phone 2','Test phone 3'); 

foreach($myarray as $data)
{

 ?>
 <form method="post">
<div class = "container well">

<div class = "ProductTitle">
<?php echo $data; ?>
</div>

<input class="Product" type="text" name="Title"/>   
<button class = "btn btn-success" type="button" > Add</button>

</div>

 <?php

}
?>

</form>

<!-- This posts the data to the php file -->

<script type="text/javascript">

$(document).ready(function(){
   //Important for -1 as insures the current index is set to zero 


$( ".btn-success" ).click(function() {
    var x = $(this).parent().index();

var Productdata =   $('.Product').eq(x).val();


                $.ajax({
         url: 'display-data.php',
         type: 'POST',
         data: {Phonetitleclicked:Productdata}, // it will serialize the form data
                dataType: 'html'
            })
            .done(function(data){



            })


});



})
</script>
<!-- Below is the php file adding the sessions into the array -->

<?php /
 $_SESSION['cart'] = array();

  $cart_row = array(
        'product_Title'=>$_POST['Phonetitleclicked']
    );

   $_SESSION["cart"][]=$_POST['Phonetitleclicked'];
print_r($_SESSION);
 ?>

1 个答案:

答案 0 :(得分:1)

在将新商品推送到购物车时,您始终会创建覆盖旧数据的新数组。只有在尚未设置的情况下才需要创建新数组:

// Your file where you are adding items
if(!isset($_SESSION['cart'])) {
  $_SESSION['cart'] = array();
}