2011-04-06 87 views
0

我只是試圖寫一個函數在PHP中添加到折扣數組,但它似乎並沒有工作。

function addToDiscountArray($item){ 
     // if we already have the discount array set up 
     if(isset($_SESSION["discountCalculator"])){ 

      // check that this item is not already in the array 
      if(!(in_array($item,$_SESSION["discountCalculator"]))){ 
       // add it to the array if it isn't already present 
       array_push($_SESSION["discountCalculator"], $item); 
      } 
     } 
     else{ 

      $array = array($item); 
      // if the array hasn't been set up, initialise it and add $item 
      $_SESSION["discountCalculator"] = $array; 
     } 
} 

我每次刷新它就像$ _SESSION [「discountCalculator」]尚未建立的頁面,但我不明白爲什麼。寫作時,我可以以正常的方式在foreach php循環中使用$ _SESSION [「discountCalculator」]?

非常感謝

+4

在做任何事情之前你做過'session_start()'嗎? ''_SESSION'總是存在,但是在執行'session_start()'後會只填充存儲的值' – 2011-04-06 16:30:49

+0

非常感謝,我最初編寫了頭文件,並且在那裏有session_start(),所以假設它仍然會是的,但現在自從你提到它以來我就去檢查它了,看起來我正在構建該網站的人之一在他調整模板時已將其取出。謝謝 – ComethTheNerd 2011-04-06 16:35:00

回答

1

,每次$_SESSION['discountCalculator']似乎並沒有被設置的事實,可能是因爲$_SESSION未設置(NULL)。這種情況主要發生在您頁面開始時未執行session_start()時。 嘗試在函數的開頭添加session_start()

function addToDiscountArray($item) { 
    if (!$_SESSION) { // $_SESSION is NULL if session is not started 
     session_start(); // we need to start the session to populate it 
    } 
    // if we already have the discount array set up 
    if(isset($_SESSION["discountCalculator"])){ 

     // check that this item is not already in the array 
     if(!(in_array($item,$_SESSION["discountCalculator"]))){ 
      // add it to the array if it isn't already present 
      array_push($_SESSION["discountCalculator"], $item); 
     } 
    } 
    else{ 

     $array = array($item); 
     // if the array hasn't been set up, initialise it and add $item 
     $_SESSION["discountCalculator"] = $array; 
    } 
} 

注意,如果會話已經啓動,這不會影響函數。如果會話未啓動,它將只運行'session_start()`。

+0

感謝您的意見,我覺得自己像一個白癡,因爲我最初在標題腳本中有這個,但正如我上面解釋的,似乎我的一個合作者已經在某個時候刪除了它......現在它回到了它現在所屬的位置! – ComethTheNerd 2011-04-06 16:47:29

+0

@Greenhouse,這個答案解決了你的問題嗎? – Shoe 2011-04-06 16:48:03