2012-08-02 80 views
0

下面的代碼將增加/減少一週1: (是的,我的應用程序需要的值存儲在一個$_SESSION

if (isset($_POST['decrease'])) { 
    $week_value = ($_SESSION['sess_week'] = $_SESSION['sess_week']-1); 
} 
else if (isset($_POST['increase'])) { 
    $week_value = ($_SESSION['sess_week'] = $_SESSION['sess_week']+1); 
} 
else { 
    $week_value = ($_SESSION['sess_week'] = date('W')); 
} 

echo $week_value; 

不過。我想在第52周(新的一年)重置,我該怎麼做?我是編程新手。

回答

1
if (isset($_POST['decrease'])) { 
    $week_value = $_SESSION['sess_week'] == 1 ? 52 : --$_SESSION['sess_week']; 
} 
else if (isset($_POST['increase'])) { 
    $week_value = $_SESSION['sess_week'] == 52 ? 1 : ++$_SESSION['sess_week']; 
} 
else { 
    $week_value = ($_SESSION['sess_week'] = date('W')); 
} 
+0

感謝大家的快速回復。我使用@xdazz代碼。它像一個魅力一樣工作! – David 2012-08-02 08:39:32

1

您可以使用date("W")函數獲取當前時間的星期編號。第1周,簡單地將它設置爲1(或者如果您從那裏開始,則爲0)。

您可以使用mktime()作爲日期函數中的第二個參數進行測試,以驗證輸出。

<?php 

    if (date("W")==1) 
    { 
     $week_value =1; 
    } 
    else 
    { 
     if (isset($_POST['decrease'])) { 
      $week_value = ($_SESSION['sess_week'] = $_SESSION['sess_week']-1); 
     } 
     else if (isset($_POST['increase'])) { 
      $week_value = ($_SESSION['sess_week'] = $_SESSION['sess_week']+1); 
     } 
     else { 
      $week_value = ($_SESSION['sess_week'] = date('W')); 
     } 
    } 

?> 
-1

試試這個:

if($week_value == 52)$week_value = 0; 
+1

如果此人未登錄這可能無法正常工作一會兒。 – Fluffeh 2012-08-02 08:27:23

1

一種可能做到這一點如下。 (我認爲你的意思是,如果一週超過52,它應該是1.此外,我加 ,如果一週下降到1以下,它應該再次52,因此是去年的最後一週)。

if (isset($_POST['decrease'])) 
{ 
    $week_value=$_SESSION['sess_week']-1; 
} 
else 
{ 
    if (isset($_POST['increase'])) 
    { 
      $week_value=$_SESSION['sess_week']+1; 
    } 
    else 
    { 
      $week_value=date('W'); 
    } 
} 

if ($week_value>52) 
{ 
    $week_value=1; 
} 
else 
{ 
    if ($week_value<1) 
      $week_value=52; 
} 
$_SESSION['sess_week']=$week_value; 
0

待辦事項模(%)與52

這樣,你能保證你一週將始終小於52