2011-04-06 7 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"]을 사용할 수 있습니까? $_SESSION이 (NULL) 설정되어 있기 때문에

많은 감사

+4

무엇을하기 전에'session_start()'를 했습니까? '$ _SESSION'은 항상 존재하지만,'session_start()'를 수행 한 후에 만 ​​저장된 값으로 채워질 것입니다. –

+0

고맙습니다. 처음에는 헤더 스크립트를 썼고 거기에 session_start()를 넣어 두었습니다. 하지만, 지금은 당신이 그것을 언급 한 이래로 나는 그것을 확인하기 위해 갔다. 그리고 그가 웹 사이트를 만들고있는 사람들 중 하나가 그가 템플릿을 조정할 때 그것을 꺼냈다 고 보인다. 감사합니다 – ComethTheNerd

답변

1

마다 $_SESSION['discountCalculator'] 설정되지 보인다는 사실은, 수 있습니다. 이 경우는 시작 페이지에서 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

+0

Greenhouse,이 대답이 당신에게 문제를 해결 했습니까? – Shoe