用点表示法写会话数据



我这样添加会话变量:

foreach ( $data as $key => $value ) {
  $this->Session->write("MyVariable.$key", $value );
}

是否可以在不传递键的情况下向会话变量数组添加元素?
我的意思是像这样:

$MyArray[] = "apple";
$MyArray[] = "banana";

那么可以这样添加吗?伪代码:

$this->Session->write('MyVariable'.[], "apple");
$this->Session->write('MyVariable'.[], "banana");

编辑:$data数组是一个例子。要保存的数据不是数组。它是一个字符串。每次我添加到会话变量,我不想给代码键。我想知道是否有可能开箱即用。在我当前的代码中,我是这样做的:

    $newKey = count( $this->Session->read("MyVariable") );
    $this->Session->write("MyVariable.$newKey", "apple");

嗨,我想应该是这样的:

foreach ( $data as $key => $value ) {
  $this->Session->write('MyVariable.'.$key, $value );
}

你必须在引号内加一个点

如果您不想每次都给出键值,那么将其存储为一个数组,如@mark said

$this->Session->write("MyVariable", $data);

如果您想在代码的其他部分向$data数组添加一个新值,则必须执行如下操作:

$data = $this->Session->read("MyVariable");
$data[] = array('other'=>'value');
$this->Session->write("MyVariable", $data);

或者添加确切的键,如@mmahgoub所说的

$this->Session->write("MyVariable".$key, $value);

最新更新