【问题标题】:Session::instance() and push array data to session arraySession::instance() 并将数组数据推送到会话数组
【发布时间】:2010-07-31 16:28:12
【问题描述】:

例如我有 Session::instance()->get('orders') 这是一些数组的数组:

$first = array('id' = 1, 'name' => 'first', 'price' => 100); $second = array('id' => 2, 'name' => 'second', 'price' => 200); $_SESSION['orders'] = array($first, $second);

但是如果我用这个

Session::instance()->set('orders', array(array('id' => 3, 'name' => 'third', 'price' => 300)));

这将删除第一个订单(id 1,id 2)。 那么我怎样才能将数据数组添加到名为“订单”的会话数组中而不是删除数据数组? array_push 还是别的什么?

【问题讨论】:

标签: session kohana


【解决方案1】:

编辑,没看到你的评论,很完美。

不言自明。

$session = Session::instance();

// Find existing data
$data = $session->get('orders');

// Add new array
$data[] = array('id' => 3, 'name' => 'new data', 'price' => 300);

// Resave it
$session->set('orders', $data);

【讨论】:

  • 我还发现我们可以初始化 $_SESSION 数组并像在原始 php 代码中一样使用它。我的意思是将 Session::instance() 链接到 $_SESSION 数组,因为在 kohana 中我们无法使用$_SESSION 数组默认直接。
【解决方案2】:

对于我来说,我认为最好的方法是:

public function before() {
...
$this->variable = Session::instance()->get('key', array());
...
}

一些代码...

public function after() {
...
Session::instance()->set('key', $this->variable, Date::MINUTE);
...
}

【讨论】:

    猜你喜欢
    • 2021-08-06
    • 2017-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-31
    • 1970-01-01
    • 2015-03-31
    相关资源
    最近更新 更多