繁体   English   中英

PHP会话购物车数组输入循环

[英]Php session shopping cart array loop of inputs

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

<?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);
 ?>

当将新项目推送到购物车时,您总是在创建新的数组,该数组将覆盖旧数据。 仅在尚未设置时才需要创建新数组:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM