我可以在 php 中的 SESSION 数组上使用 array_push 吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2616540/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I use array_push on a SESSION array in php?
提问by zeckdude
I have an array that I want on multiple pages, so I made it a SESSION array. I want to add a series of names and then on another page, I want to be able to use a foreach loop to echo out all the names in that array.
我有一个需要在多个页面上显示的数组,因此我将其设为 SESSION 数组。我想添加一系列名称,然后在另一个页面上,我希望能够使用 foreach 循环来回显该数组中的所有名称。
This is the session:
这是会议:
$_SESSION['names']
I want to add a series of names to that array using array_push like this:
我想使用 array_push 向该数组添加一系列名称,如下所示:
array_push($_SESSION['names'],$name);
I am getting this error:
我收到此错误:
array_push() [function.array-push]: First argument should be an array
array_push() [function.array-push]:第一个参数应该是一个数组
Can I use array_push to put multiple values into that array? Or perhaps there is a better, more efficient way of doing what I am trying to achieve?
我可以使用 array_push 将多个值放入该数组吗?或者也许有更好,更有效的方式来做我想要实现的目标?
回答by Your Common Sense
Yes, you can. But First argument should be an array.
是的你可以。但第一个参数应该是一个数组。
So, you must do it this way
所以,你必须这样做
$_SESSION['names'] = array();
array_push($_SESSION['names'],$name);
Personally I never use array_push as I see no sense in this function. And I just use
我个人从不使用 array_push,因为我认为这个函数没有意义。我只是用
$_SESSION['names'][] = $name;
回答by hsz
Try with
试试
if (!isset($_SESSION['names'])) {
$_SESSION['names'] = array();
}
array_push($_SESSION['names'],$name);
回答by Ravi Mane
$_SESSION['total_elements']=array();
array_push($_SESSION['total_elements'], $_POST["username"]);
回答by internals-in
<?php
session_start();
$_SESSION['data']= array();
$details1=array('pappu','10');
$details2=array('tippu','12');
array_push($_SESSION['data'],$details1);
array_push($_SESSION['data'],$details2);
foreach ($_SESSION['data'] as $eacharray)
{
while (list(, $value) = each ($eacharray))
{
echo "Value: $value<br>\n";
}
}
?>
output
输出
Value: pappu
Value: 10
Value: tippu
Value: 12
值:pappu
值:10
值:tippu
值:12
回答by Ajay Jaiswal
Try this, it's going to work :
试试这个,它会起作用:
session_start();
if(!isset($_POST["submit"]))
{
$_SESSION["abc"] = array("C", "C++", "JAVA", "C#", "PHP");
}
if(isset($_POST["submit"]))
{
$aa = $_POST['text1'];
array_push($_SESSION["abc"], $aa);
foreach($_SESSION["abc"] as $key => $val)
{
echo $val;
}
}

