Zend Framework 2 - Sessions containing multidimensional arrays

Deadly 提交于 2020-01-05 21:07:52

问题


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:


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.



来源:https://stackoverflow.com/questions/31022396/zend-framework-2-sessions-containing-multidimensional-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!