会话值不打印其他键及其值

时间:2016-10-03 19:03:33

标签: php session

我可以设置此会话值。

<?php
  require_once 'less.php/Less.php';

  $parser = new Less_Parser();
  $parser->parseFile( 'Z:\home\test1\www\assets\bootstrap\less\bootstrap.less', 'test' );
  $css = $parser->getCss();
?>

但是当我运行这个

<?php
  $_SESSION['cart_items'][$name]['price']=$price;
  if (!empty($quantity)) {
    $_SESSION['cart_items'][$name]['quantity']=$quantity;
  }
?>

仅打印<?php foreach($_SESSION['cart_items'] as $key => $value) { echo $key ; echo $value; //echo "<br>prod product_price : ".$product_price; } ?> 。它不会打印数量值。如何打印$_SESSION['cart_items'][$name]['price']价格,数量等。

这是我的完整代码:

$name

3 个答案:

答案 0 :(得分:1)

你有一个多维数组:

$_SESSION['cart_items'][$name]['quantity']=$quantity;
     ^--#1     ^--#2     ^--#3

因为这是你的预言:

foreach($_SESSION['cart_items'] as $key => $value){
               ^--#1                         ^--#2

意味着当你echo $value时,你正试图回应一个数组。你需要另一个循环才能达到第三维:

foreach($_SESSION['cart_items'] as $key => $item) {
              ^--#1                         ^--#2
   foreach($item as $key2 => $value) {
             ^--#2             ^--#3

答案 1 :(得分:1)

创建新项目时,需要在[$ name]处创建数组,因为Item是一个数组。 如果不这样做,你试图分配一个值就像它是一个数组,但它只是一个简单的值。

<?php 

    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{
        //Since your item is an array, you need to create it.
        $_SESSION['cart_items'][$name] = array();
        $_SESSION['cart_items'][$name]['price']=$price;

        if (!empty($quantity)){
              echo "adding qty";
            $_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);
    }

答案 2 :(得分:0)

试试此代码

<?php
  if (!isset($_SESSION['cart_items'])) {
    $_SESSION['cart_items'] = array();
  }
  $z = $_SESSION['cart_items'];
  $q = array_column($z, 'name');
  if (array_key_exists($id, $q)){
    header('Location: products.php?action=exists&id' . $id . '&name=' . $name);
  } else {
    if (!empty($quantity)) {
      array_push($_SESSION['cart_items'], array('name' => $name, 'quantity' => $quantity, 'price' => $price));
    }
    header('Location: products.php?action=added&id' . $id . '&name=' . $name);
  }

?>

然后你可以回复所有项目

<?php
  $f = $_SESSION['cart_items'];
  $d = array_column($f, 'name');
  $s = array_column($f, 'quantity');
  $t = array_column($f, 'price');
  static $x = 1;
  while (count($d) > $x) {
    echo $d[$x];
    echo $s[$x];
    echo $t[$x];
    $x++;
  }

?>