【问题标题】:How expand my session array to have more value?如何扩展我的会话数组以获得更多价值?
【发布时间】:2016-09-30 03:06:08
【问题描述】:

目前,我可以在我的会话数组中设置并保留所选产品的名称和价格。我需要扩展,以便我可以保持数量和 id。我不知道如何将更多的值存储到同一个数组中,这样如果可能的话,键是 id?其次,我需要检查用户是否再次按下,然后只添加数量,其余信息保持不变?

$id = isset($_GET['id']) ? $_GET['id'] : "";
$name = isset($_GET['name']) ? $_GET['name'] : "";
$price = isset($_GET['price']) ? $_GET['price'] : "";
$quantity = isset($_GET['quantity']) ? $_GET['quantity'] : "";

/*
 * check if the 'cart' session array was created
 * if it is NOT, create the 'cart' session array
 */
if(!isset($_SESSION['cart_items'])){
    $_SESSION['cart_items'] = array();
}

// check if the item is in the array, if it is, do not add
if(array_key_exists($id, $_SESSION['cart_items'])){
    // redirect to product list and tell the user it was added to cart
    header('Location: products.php?action=exists&id' . $id . '&name=' . $name);
}

// else, add the item to the array
else{
    $_SESSION['cart_items'][$name]=$price;

    // redirect to product list and tell the user it was added to cart
    header('Location: products.php?action=added&id' . $id . '&name=' . $name);
}

【问题讨论】:

  • 它的数组和其他数组一样
  • 我更喜欢数组,所以我的键是 $id,然后是数量、价格、名称等。我需要像现在这样动态地存储它们。接下来我需要for循环来提取每个信息。
  • $price = $_GET['price'] 只是提示您前进,不要让用户自己设定价格 - 这样您可能会赔钱。
  • 是的,那么如何设置不被获取,因为它将是他们提交的链接?
  • 我不明白为什么当我展示我所做的事情并给出我的代码时它被否决了

标签: php arrays session


【解决方案1】:

我想你可能想使用multidimensional array

// else, add the item to the array
else{
    $_SESSION['cart_items'][$name]['price']=$price;

    if (!empty($quantity)){
        $_SESSION['cart_items'][$name]['quantity']=$quantity;
    }

    // redirect to product list and tell the user it was added to cart
    header('Location: products.php?action=added&id' . $id . '&name=' . $name);
}

更新: 为了访问数组的更深维度,您可以使用嵌套循环。

foreach($_SESSION['cart_items'] as $name=>$value){
    foreach($value as $key => $val){
        echo "$name : $key = $val <br/>\n";
    }
}

【讨论】:

  • 如何读取这些值,因为目前我只是这样做 foreach($_SESSION['cart_items'] as $name=>$value){ 那么对于新方法如何接收这些值?跨度>
  • 试过你的方法,但是当我运行 foreach 时它根本不打印任何东西。
  • This foreach foreach($_SESSION['cart_items'] as $name=>$value){ foreach($value as $key => $val){ echo "$name : $key = $ val
    \n"; } } 没有打印任何东西?我可以一次获得每个名称的价格,数量吗
猜你喜欢
  • 2018-03-21
  • 1970-01-01
  • 1970-01-01
  • 2021-11-28
  • 2018-05-07
  • 2021-03-12
  • 1970-01-01
  • 2017-10-23
  • 2020-02-11
相关资源
最近更新 更多