繁体   English   中英

如何在数组中存储多个值

[英]How to store multiple values in array

我想每次将一些值传递给此页面(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

您总是会覆盖该数组,因此只能在其中获得一个值。 尝试这个:

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;
            }
        }

暂无
暂无

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

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