在PHP Session变量中增加数组值

时间:2011-10-23 18:40:26

标签: php

我在PHP会话中有这个数组,我想一步一步地完成。

如何获取当前数组索引并向前或向后移动一步?这是代码:

for ($i = 0; $ < 10; $i++){    
    $result_array[] = $i;   
}

$_SESSION['theValue'] = $result_array;

我试过了:

$_SESSION['theValue'] [0]++;

一次一步地移动数组,但它只在该索引处显示相同的值。有没有办法可以继续增加索引?

我不确定我是否有多大意义。

3 个答案:

答案 0 :(得分:4)

$_SESSION['theValue'] [0]++实际上会增加数组中的第一个值,而不是递增数组索引。使用数组函数,尤其是keynext来导航数组。

或者,如果要在会话中保留最后一个数组索引,则可能希望将索引存储为单独的会话值。使用count($array)读取数组的长度。索引从0count - 1

答案 1 :(得分:3)

如果我正确理解你的问题,你想循环遍历数组,那么你应该做这样的事情:

$size = count($_SESSION['theValue']);
for($i=0; $i < $size; $i++)
{
    $currentValue = $_SESSION['theValue'][$i];
}

确保size是一个局部变量,并且你没有在for循环中直接使用count()。

你做$ _SESSION ['theValue'] [0] ++的方法实际上会增加零指数的值。

答案 2 :(得分:1)

init session array

$_SESSION['theValue'] = $result_array;
$_SESSION['currentIndex'] = 0;

创建下一个/上一个按钮

$prev = $_SESSION['currentIndex'] == 0 ? 0 : $_SESSION['currentIndex'] - 1;
$next = $_SESSION['currentIndex'] == sizeof($_SESSION['theValue']) ? $_SESSION['currentIndex'] : $_SESSION['currentIndex'] + 1;

然后转到下一页/上一页,只需递增/递减$_SESSION['currentIndex']


用例:
所以当你创建这样的链接时:

<a href="index.php?page=1">Next</a>
<a href="index.php?page=0">Prev</a>

您需要捕获$_GET['page']的值并在呈现内容之前将其保存到currentIndex会话属性。

if(isset($_GET['page'])){
    if(is_numeric($_GET['page']){
        if($_GET['page'] >= 0 && $_GET['page'] <= sizeof($_SESSION['theValue'])){
            $_SESSION['currentIndex'] = $_GET['page'];
        }
    }
}
// place code which works with 'currentIndex' and array in session here...
相关问题