如何在Codeigniter中按页码排除最多n页的会话数据?

时间:2015-02-17 07:25:06

标签: php codeigniter session

$this->session->unset_userdata('current_page_'.$pagenumber);

通过使用此代码,我从会话中为每个页码取消设置数据,但问题是在某些时候我不知道会话中存在多少页数据,例如:

$this->session->unset_userdata('current_page_'.1);
$this->session->unset_userdata('current_page_'.2);
$this->session->unset_userdata('current_page_'.3);
$this->session->unset_userdata('current_page_'.4);
.
.
.
$this->session->unset_userdata('current_page_'.?????);

有没有办法从会话中取消设置数据,例如“current_page_%”这样的密钥 提前谢谢。

4 个答案:

答案 0 :(得分:1)

您可以尝试搜索会话的首字母current_page_并相应地取消设置。

<?php
function startsWith($haystack, $needle) {
    // search backwards starting from haystack length characters from the end
    return $needle === "" || strrpos($haystack, $needle, -strlen($haystack)) !== FALSE;
}

foreach($this->session->all_userdata() as $key => $value)
{
    if(startsWith($key, 'current_page_'))
        $this->session->unset_userdata($key);
}


例如:

<?php
function startsWith($haystack, $needle) {
    // search backwards starting from haystack length characters from the end
    return $needle === "" || strrpos($haystack, $needle, -strlen($haystack)) !== FALSE;
}

$session = array(
            'current_page_12' => 'abc', 
            'current_page_qw1' => 'xyz', 
            'hello' => 'world', 
            'current_page_23d' => 'mno', 
            'example' => '112'
        );

foreach($session as $key => $value)
{
    if(startsWith($key, 'current_page_'))
        unset($session[$key]);
}

print_r($session);


输出:

Array
(
    [hello] => world
    [example] => 112
)


演示:
http://3v4l.org/uh4HK

答案 1 :(得分:0)

试试这个

$j = 1;
for($i=0;$i==$j;$i++)
{
    if($this->session->userdata('current_page_'.$i))
    {
        $this->session->unset_userdata('current_page_'.$i);
        $j++;
    }else
    {
        break;
    }
}

答案 2 :(得分:0)

此语句将打印所有会话数据,您可以从中获取所有页码。

的print_r($这 - &GT;会话而&GT; all_userdata());

答案 3 :(得分:0)

这应该适合你:

(这里我只使用preg_grep()来获取遵循模式的所有数组元素。为了匹配键而不是值,我使用array_keys()来获取所有键。然后我只是循环通过匹配foreach循环并取消设置数组元素)

<?php


    //As an example v Here just use your array
    $array = array("current_page_1" => 1, "current_page_1345" => 2, "current_page_12" => 3, "current_page_34" => 4, "xy" => 5, "z" => 6);
    $sub = preg_grep("/(current_page_)\d+/", array_keys($array));

    foreach($sub as $v)
        unset($array[$v]);  //$this->session->unset_userdata($v);

    print_r($array);

?>

输出:

Array ( [xy] => 5 [z] => 6 )