将数组添加到现有的$ _SESSION数组

时间:2016-01-26 15:08:04

标签: php arrays session

我在$_SESSION

中关注了现有数组
[wishList] => wishList Object
(
[contents] => Array
(
[109] => Array
(
[qty] => 1.0000
)

[89] => Array
(
[qty] => 1.0000
)

[62] => Array
(
[qty] => 1.0000
)

现在我正在尝试像这样添加一个新对象:

echo $_SESSION['wishList']->contents = array('60' => array('qty' => '1.0000'));

所以数组看起来像这样:

[wishList] => wishList Object
    (
    [contents] => Array
    (
    [109] => Array
    (
    [qty] => 1.0000
    )

    [89] => Array
    (
    [qty] => 1.0000
    )

    [62] => Array
    (
    [qty] => 1.0000
    )

    [60] => Array
    (
    [qty] => 1.0000
    )

这不是我尝试的方式。我的错在哪里?

3 个答案:

答案 0 :(得分:1)

Tr this: -

array_push($_SESSION['wishList']->contents,array('60' => array('qty' => '1.0000')));

或试试这个: -

array_push($_SESSION['wishList']->contents[$pid] = array('qty' => '1.0000')); // where $pid = 60;

答案 1 :(得分:0)

$_SESSION['wishList']->wishList['contents'] = "your new value string or array";

你错过了选择主要对象。

我尝试了一段代码。这适合我。

session_start();
class newObject {
    var $aProp  = array("type1"=>"test1", "type2"=>"test2");
    function __contruct() {
        return array("type1"=>"test1", "type2"=>"test2");
    }
}
$newObject  = new newObject;
$_SESSION["newObj"] = $newObject;
print_r($_SESSION);
// prints Array ( [newObj] => newObject Object ( [aProp] => Array ( [type1] => test1 [type2] => test2 ) ) ) 
echo "<br>";
$_SESSION["newObj"]->aProp  = array("type3"=>"test3", "type4"=>"test4");
// prints Array ( [newObj] => newObject Object ( [aProp] => Array ( [type3] => test3 [type4] => test4 ) ) )
print_r($_SESSION);

据我说..你错过的是指出正确的目标。在你的情况下,它是$_SESSION['wishList']->wishList['contents']

答案 2 :(得分:0)

$_SESSION['wishList']->contents[60] = array('qty' => '1.0000');

这会通过将数组$_SESSION['wishList']->contents的值设置为数组来更改数组60