简体   繁体   中英

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['ScoreCardCriteria'][] = '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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM