2

我正在为 php 会话创建一个多维数组。这是代码:

    <?php
    session_start();
    // store session data

    $products = array();
    $_SESSION['Products'] = $products;

    $products[]= array("Brand"=>$_POST['Brand']);

    //retrieve session data
    echo "Product Name = ". $_SESSION['Products'][$products][0]["Brand"];

    echo "Product Name = ". $products[0]["Brand"];

    ?>

$_POST['Brand']可以是任何东西"Adidas"

我想要的是这样的:

Array Session 'Products'

   Array '$products'

     Sub-Array 'array'
           (
               "Brand" => "Adidas"
           )

     Sub-Array 'array'
           (
               "Brand" => "Nike"
           )

     Sub-Array 'array'
           (
               "Brand" => "Puma"
           )

等等。

现在echo "Product Name = ". $products[0]["Brand"];给我Product Name = Adidas

echo "Product Name = ". $_SESSION['Products'][$products][0]["Brand"];只是给了我Product Name =

我的问题是,在我的情况下,从多维数组中回显数据的正确方法是什么?

谢谢

已编辑

好的,我已将代码修改为:

    <?php
    session_start();
    $_SESSION['Products']= array("Brand"=>"Adidas");

    echo "Product Name = ". $_SESSION['Products']["Brand"];
    ?>

如果我只这样做,那么它会打印Product Name = Adidas

但是,如果我这样做:

    <?php
    session_start();
    $_SESSION['Products']= array("Brand"=>"Adidas");
    $_SESSION['Products']= array("Brand"=>"Puma");

    echo "Product Name = ". $_SESSION['Products'][0]["Brand"];
    echo "Product Name = ". $_SESSION['Products'][1]["Brand"];
    ?>

然后再次没有运气。理论上这不应该工作吗?

4

2 回答 2

1

您应该更改这两个语句的顺序:

$_SESSION['Products'] = $products;

$products[]= array("Brand"=>$_POST['Brand']);

现在您正在分配一个空数组,并且在您向变量$_SESSION['Products']添加值时不会更新。$products

所以:

$products[]= array("Brand"=>$_POST['Brand']);

$_SESSION['Products'] = $products;
于 2013-05-12T02:55:30.163 回答
1

1)改变分配的顺序

$products[] = array("Brand"=>$_POST['Brand']);
$_SESSION['Products'] = $products;

代替

$products[] = array("Brand"=>$_POST['Brand']);
$_SESSION['Products'] = $products;

2)更正您的会话变量

$_SESSION['Products'][0]["Brand"]

代替

$_SESSION['Products'][$products][0]["Brand"]

更新这是您更新问题的解决方案:

$_SESSION['Products'][] = array("Brand"=>"Adidas");
$_SESSION['Products'][] = array("Brand"=>"Puma");

echo "Product Name = ". $_SESSION['Products'][0]["Brand"];
echo "Product Name = ". $_SESSION['Products'][1]["Brand"];
于 2013-05-12T02:57:44.400 回答