簡體   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