开发者

CakePHP - how to push array in Session?

If I have the following,

$this->Session->write('ScoreCardCriteria', 'test');

And want to add another item to ScoreCardCriteria as an array of items, how would I do so?

With regular PHP, It would be something like

$_SESSION['ScoreCard开发者_StackOverflowCriteria'][] = 'test';

I came up with this:

    $new_array = array_merge((array)$this->Session->read('ScoreCardCriteria'), array('test'));
    $this->Session->write('ScoreCardCriteria', $new_array);

But I'd love it if there was a more "cake" way to do it.


You could do this:

$this->Session->write('ScoreCardCriteria', array( 'test' ) );

And then:

$data = $this->Session->read('ScoreCardCriteria');
$data[] = 'test';
$this->Session->write('ScoreCardCriteria', $data);

However, to be quite honest, CakePHP uses the $_SESSION object internally and just overrides the default session handlers. The only thing ->write does is parse a dot notated set path (which would look like foo.bar.x) which you are not doing. And echo debug information if you are watching particular values. It shouldn't hurt if you modify $_SESSION directly.


You need to read the session data and then merge it with your data to be appended. You should also check if the session data exists before doing so:

if ($this->Session->check('ScoreCardCriteria')) {
    $this->Session->write('ScoreCardCriteria', am(
       $this->Session->read('ScoreCardCriteria'),
       array('test')
    ));
} else {
    $this->Session->write('ScoreCardCriteria', array('test'));
}

Hope that helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜