[英]PHP session records return only one record
I have multiple record for the session $_SESSION["cart_array"]
like 我在会话
$_SESSION["cart_array"]
有多个记录,例如
$_SESSION["cart_array"] = array(0 => array("item_id" => sms, "quantity" => $pe, "to" =>$to, "msg" => $message));
please see here https://ideone.com/NZysQc 请在这里查看https://ideone.com/NZysQc
In my achievement I was trying to output this record in a different page but it output only one record. 为了达到我的成就,我试图在另一页中输出该记录,但仅输出一个记录。 What is mine doing wrong?
我做错了什么? This is my tried code:
这是我尝试的代码:
foreach ($_SESSION["cart_array"] as $each_item) {
$id = $each_item['item_id'];
$to = $each_item['to'];
echo '$to and $id';
}
But it return only one record in the session. 但它在会话中仅返回一条记录。
My suggestion would be as such:- 我的建议是这样的:
$_SESSION["cart_array"][] = array("item_id" => $sms, "quantity" => $pe, "to" => $to, "msg" => $message);
to form the array and 形成数组并
foreach ($_SESSION["cart_array"] as $each_item) {
$id = $each_item['item_id'];
$to = $each_item['to'];
echo "$to and $id";
}
for the loop, notice the double quotes in the echo
. 对于循环,请注意
echo
的双引号。
Change 更改
echo '$to and $id';
For: 对于:
echo "$to and $id";
As vars are not parsed inside simple quoted strings. 由于var不会在简单的带引号的字符串中进行解析。
Your example has only the element 0, so only one element will be shown. 您的示例仅包含元素0,因此将仅显示一个元素。
You could array_push your elements to you cart session var to have more than one element. 您可以将您的元素array_push到购物车会话var中以拥有多个元素。 And set it to the new array only if the var is stil not set.
并仅在未设置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.