2015-10-06 40 views
-1

我想在每次向页面传递一些值时向数组添加多个值(cart.php)。如何在数组中存储多个值

,但现在我能够从array.i只得到一个价值也试过

echo $_SESSION['cart'][1]; 
echo $_SESSION['cart'][2]; 

,但我能得到新添加只有一个值,我收到通知

Notice: Undefined offset: 1 
Notice: Undefined offset: 2 

cart.php

<?php 
    if(isset($_GET['action']) && isset($_GET['product_id'])){ 
      if($_GET['action'] == "add"){ 
       $product_id = $_GET['product_id']; 
       $_SESSION['cart'] = array(); 
       array_push($_SESSION['cart'],$product_id);  
      } 
     } 
?> 

我这是怎么传递值查询字符串

http://localhost/mycart.php?action=add&product_id=4 
+0

我认为有没有必要'的product_id parameter' ......因为你在使用'session'拿到产品。 –

+0

您只传递一个product_id,并且此产品ID应位于数组的位置零,因此您必须以此方式回显echo $ _SESSION ['cart'] [0];看到的结果或只是做var_dump/print_r数组 – Tommy

+0

@汤米是啊,但它存储在[0]的一切; 。 –

回答

2

你总是覆盖数组,所以你只能得到一个值。 试试这个:

if(isset($_GET['action']) && isset($_GET['product_id'])){ 
      if($_GET['action'] == "add"){ 
       $product_id = filter_var($_GET['product_id'], FILTER_SANITIZE_NUMBER_INT); 
       $_SESSION['cart'][] =$product_id; 
      } 
     } 
+0

array_push也有相同的效果 – Tommy

+1

看看所有的代码,基本上,我把一行写了,所以它可以和array_push或$ myArray []一起使用,但是像php.net文档中所说的,最好使用$ myArray []。 http://php.net/array_push – Paladin