duanchi1230 2015-06-24 09:10
浏览 45

Zend Framework 2 - 包含多维数组的会话

Suppose i have the following set of data:

$foobar = array(
    "foo" => array (
       "foo1" => 1,
       "foo2" => 2,
       "foo3" => 3
    ),
    "bar" => array (
        "bar1" => 1,
        "bar2" => 2,
        "bar3" => 3,
    ),
);

In standard PHP, i could do the following:

$_SESSION['foobar'] = $foobar;

Then, to call values, by example bar2:

$_SESSION['foobar']['bar']['bar2'];

But what about doing this in Zend Framework 2?

I have already set bootstrap with all parameters for session manager, and container has been set with it. Sessions get created. So, if i do, by example:

$session = new Container('foobar');

and put a value in there:

$session->foo1 = 1;

this works. Same if i decide to put an array as session variable:

//placing the $foobar array defined before
$session->foobar = $foobar;

But i don't know how can i call values. Supposing i want foo2, i'd do

echo $session->foobar->foo->foo2;

expecting it would output '2', but i get an error instead:

So i tried doing

echo $session->foobar['foo']['foo2'];

but this returns another error.

So now i don't know what should i do to gather those data, or how could i store session variables differently. I need this to make a shopping cart, so foo and bar are different products. How could i do this?

  • 写回答

1条回答 默认 最新

  • duanbairan4235 2015-06-24 10:34
    关注

    Solved. First of all i created the parent offset this way:

    $session->offsetSet("foobar", new ArrayObject());
    

    (you need use Zend\Stdlib\ArrayObject; on top of your script).

    Now i can create anything from there:

    $session->foobar->foo = "foo1";
    $session->foobar->bar = "bar1";
    

    and so going on. To get them, it's as easy as it should:

    echo $session->foobar->foo; //returns foo1
    

    I hope this will help someone.

    评论

报告相同问题?

悬赏问题

  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计