2013-05-12 54 views
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"]; 
    ?> 

然後再次沒有運氣。理論上不應該這樣工作?

+2

調試與'的print_r($ _ SESSION)'。你會看到結構。你不應該做'$ _SESSION ['Products'] = $ products;''_before_你已經填充了'$ products'數組。之後這樣做,因爲數組不是通過PHP中的引用分配的。 – 2013-05-12 02:54:58

回答

1

1)改變assignings的順序

$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"] 

UPDATE這是給你更新的問題的解決方案:

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

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

謝謝zavg,那就是訣竅! – user2028856 2013-05-12 03:14:47

+0

@ user2028856看,我已經更新了答案 – zavg 2013-05-12 03:16:53

1

你應該更改這兩個語句的順序:

$_SESSION['Products'] = $products; 

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

現在你分配一個空數組$_SESSION['Products'],當你添加值到您$products變量不會得到更新。

所以:

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

$_SESSION['Products'] = $products; 
+0

好吧,請看看我的編輯代碼 – user2028856 2013-05-12 03:06:35