0

给定以下代码:

session_start();

$cart = $_SESSION['cart'];

print_r($_SESSION['cart']);

然后我可以看到我想要访问的内容:

数组 ( [153c740f526f2fa8aac9e1ddfdce2716] => 数组 ( [deal_id] => 38 [variation_id] => [variation] => [quantity] => 6 [data] =>......

还有更多,但这是基础......

我想要做的是获取并设置数量:

所以我试过:

$cart = $_SESSION['cart'];

for ($i = 0 ; $i < count($cart) ; $i ++)
{
    echo "The session variable you want" . $_SESSION['cart'][$i]['deal_id'];
    echo "<br>";

}

但是没有输出,我做错了什么?

4

6 回答 6

3
foreach ($_SESSION['cart'] as $k => $data) {
    echo "The session variable you want" . $data['deal_id'];
    $_SESSION['cart'][$k]['deal_id'] = 'new id';
}
于 2013-07-24T17:19:39.140 回答
1

根据您刚刚打印的数据,在“购物车”中,数组是关联的,而不是数字的。

要遍历关联数组,请使用 foreach with$someArray as $key => $val表达式

于 2013-07-24T17:19:53.730 回答
1

购物车没有被顺序索引索引,你不能那样循环它,你需要使用一个 foreach 循环:

foreach($_SESSION['cart'] as $index => $value)
  echo "Var = " . $value['deal_id'];

如果要设置值,请通过引用循环值

foreach($_SESSION['cart'] as $index => &$value)
{
  echo "Var = " . $value['deal_id'];
  $value['deal_id'] = 'newValue';
}
于 2013-07-24T17:20:42.277 回答
1

你使用 foreach 语句

foreach($cart as $key=>$value){
    echo "The session variable you want" . $value['deal_id'];
    echo "<br>";
}
于 2013-07-24T17:21:50.523 回答
1

您将通过使用foreach循环来简化事情

foreach ($_SESSION['cart'] as $k => $data) {
    echo "The session variable you want" . $data['deal_id'];
    echo "<br>";
    $_SESSION['cart'][$k] = "new Value";
}
于 2013-07-24T17:22:50.827 回答
1

使用foreach循环遍历$_SESSION数组:

foreach($cart as $k=> $value){

echo "The session variable you want" . $data['deal_id']. "<br>";
$_SESSION['cart'][$k] = "newValueGoesHere"; //setting the new value

}
于 2013-07-24T17:24:08.313 回答