代码之家  ›  专栏  ›  技术社区  ›  Jaime Montoya

在CakePHP中使用一个cookie而不是两个cookie

  •  0
  • Jaime Montoya  · 技术社区  · 6 年前

    我在CakePHP中使用两个单独的cookie来存储两个单独的数组:

    $this->Cookie->write('first', $firstArray, true, '6 months');
    $this->Cookie->write('second', $secondArray, true, '6 months');
    

    访问存储在Cookie中的阵列的方法是:

    $firstArray = $this->Cookie->read('first');
    $secondArray = $this->Cookie->read('second');
    

    我想把两者的信息放在同一个cookie中,以节省一些开销。有没有关于如何实现这一点的想法,以便我可以使用一个cookie在CakePHP中存储这两个数组,然后访问这些值?非常感谢。

    2 回复  |  直到 6 年前
        1
  •  1
  •   ndm    6 年前

    只需将两个数组嵌套在父数组中即可。数据存储为JSON字符串,因此嵌套/深度限制是PHP安装中JSON编码/解码的默认值。

    $this->Cookie->write(
        'both',
        ['first' => $firstArray, 'second' => $secondArray],
        true,
        '6 months'
    );
    
    $firstArray = $this->Cookie->read('both.first');
    $secondArray = $this->Cookie->read('both.second');
    

    另请参见

        2
  •  0
  •   Jaime Montoya    6 年前

    这就是我最终实现它的方式:

    //$variable1Array = $this->Cookie->read('variable1'); -----> BEFORE
    $variable1Array = $this->Cookie->read('Box.variable1');  -----> NOW
    
    //$variable2Array = $this->Cookie->read('variable2');  -----> BEFORE
    $variable2Array = $this->Cookie->read('Box.variable2');  -----> NOW
    
    //$this->Cookie->write('variable2', $variable2Array, true, '2 months');  -----> BEFORE
    $this->Cookie->write('Box.variable2', $variable2Array, true, '2 months');  -----> NOW
    
    //$this->Cookie->write('variable1', $variable1Array, true, '2 months');  -----> BEFORE
    $this->Cookie->write('Box.variable1', $variable1Array, true, '2 months');  -----> NOW