[英]PHP session records return only one record
我在會話$_SESSION["cart_array"]
有多個記錄,例如
$_SESSION["cart_array"] = array(0 => array("item_id" => sms, "quantity" => $pe, "to" =>$to, "msg" => $message));
請在這里查看https://ideone.com/NZysQc
為了達到我的成就,我試圖在另一頁中輸出該記錄,但僅輸出一個記錄。 我做錯了什么? 這是我嘗試的代碼:
foreach ($_SESSION["cart_array"] as $each_item) {
$id = $each_item['item_id'];
$to = $each_item['to'];
echo '$to and $id';
}
但它在會話中僅返回一條記錄。
我的建議是這樣的:
$_SESSION["cart_array"][] = array("item_id" => $sms, "quantity" => $pe, "to" => $to, "msg" => $message);
形成數組並
foreach ($_SESSION["cart_array"] as $each_item) {
$id = $each_item['item_id'];
$to = $each_item['to'];
echo "$to and $id";
}
對於循環,請注意echo
的雙引號。
更改
echo '$to and $id';
對於:
echo "$to and $id";
由於var不會在簡單的帶引號的字符串中進行解析。
您的示例僅包含元素0,因此將僅顯示一個元素。
您可以將您的元素array_push到購物車會話var中以擁有多個元素。 並僅在未設置var的情況下將其設置為新數組。
$newItem = array("item_id" => sms, "quantity" => $pe, "to" =>$to, "msg" => $message);
if (empty($_SESSION["cart_array"]))
$_SESSION["cart_array"] = array(0 => $newItem);
else
array_push($_SESSION["cart_array"], $newItem);
$_SESSION["cart_array"] = array(0 => array("item_id" => sms, "quantity" => $pe, "to" =>$to, "msg" => $message),1 => array("item_id" => sms, "quantity" => $pe, "to" =>$to, "msg" => $message));
foreach($_SESSION["cart_array"] as $each_item_array) { foreach ($each_item_array as $each_item) { $id = $each_item['item_id']; $to = $each_item['to']; echo "$to and $id </br>"; } }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.