Cakephp 3 如何制作会话数组

Cakephp 3 How to make session array

我正在尝试在控制器中编写会话。我的结构是

$_SESSION['a'][0] = 1;
$_SESSION['a'][1] = 2;
$_SESSION['a'][2] = 3;

我正在尝试这个

Configure::write('Session', ['a' =>'1'])

但它不起作用。如何在 cakephp 中做到这一点 3 方式

要在 CakePHP 3 的 Session 中写入变量,您需要编写以下代码:

$this->request->session()->write('Your Key',Your_array);

要了解更多信息,您可以访问此处:

http://book.cakephp.org/3.0/en/development/sessions.html

为了把事情说清楚:

// code writing array to session
$a = [ "abc" => "word", "123" => 42, "?" => $b ];
$a["more"] = "if you need to add";
$a[] = "whatever";
$this->request->session()->write( 'my_array', $a );
// code reading array from session
$recall = $this->request->session()->read( 'my_array' );
debug( sprintf( "What's the word? [%s]", $recall["abc"] ) );

您可以简单地使用

$session->write([
  'key1' => 'blue',
  'key2' => 'green',
]);

我指的是

http://book.cakephp.org/3.0/en/development/sessions.html#reading-writing-session-data

答案是在CakePHP中做不到3.x

在原版 PHP 中,可以这样做:

<?php
    session_start();
    $_SESSION['a'][0] = 1;
    $_SESSION['a'][1] = 2;
    $_SESSION['a'][2] = 3;
    var_dump($_SESSION);
?>

将输出:

array(1) { 
    ["a"]=> array(3) { 
        [0]=> int(1) 
        [1]=> int(2) 
        [2]=> int(3) 
    } 
}

这是正确的,应该发生什么。

在 CakePHP 中,您不能在会话密钥中指定数组。例如:

$this->request->session()->write('a[]', 1);
$this->request->session()->write('a[]', 2);
$this->request->session()->write('a[]', 3);

不会工作。

如果删除 [] 值将被覆盖。例如:

$this->request->session()->write('a', 1);
$this->request->session()->write('a', 2);
$this->request->session()->write('a', 3);

$this->request->session()->read('a') 的值将是 3。值 12 已被覆盖。同样,这是意料之中的,因为您每次都会覆盖密钥 a 。等效的香草 PHP 是:

$_SESSION['a'] = 1;
$_SESSION['a'] = 2;
$_SESSION['a'] = 3;

由于缺少索引数组,$_SESSION['a'] 每次都会被覆盖。这是正常行为。它需要有索引(例如 ['a'][0], ['a'][1], ...)才能工作!

他们给出 key1key2 之类的其他答案是不合适的。因为在很多情况下,您希望所有内容都包含在索引数组中。对于这种情况,生成单独的键名是错误的。

我对已接受答案的编辑被拒绝了,所以我提供了 - 看似必要的 - 明确 代码示例,以供 @Andy 和其他人使用。

// code to write to session
$a = [ 0 => "zero", 1 => "one", 2 => "two"  ];
$a[] = "three";
$this->request->session()->write( 'my_array', $a );

// code to read from session
$z = $this->request->session()->read( 'my_array' );
debug( $a[3] ); // outputs "three"