2011-04-06 64 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