2013-08-24 38 views
1

我有代表一個月的數據的字符串。例如,「00」是1月,「01」是2月,「02」是3月等等。 如何讓字符串表示爲「01」是1月,「02」是2月等等,這是一種更簡單的方法。我找不到任何可以做到的技巧。將字符串轉換爲整數,在其之前添加一個零?

/* 型投每月爲int,如果低於一個數字加一個零,並轉換爲字符串 ELSEIF超過9(2位)轉換爲字符串提前 */

$month = "00"; // represents January 
$month = (int) $month; 
$month += 1; 

if ($month <= 9){ 
    $month = str_pad($month, 2, "0", STR_PAD_LEFT); 
} 
elseif ($month > 9){ 
    $month = (string) $month; 
} 

感謝

回答

1

而不是使用str_pad你也可以用sprintf的:

$month = "00"; 
$month = (int) $month; 
$month += 1; 
$month = sprintf("%02s", $month); 

或者更短:

$month = sprintf("%02s", $month + 1); 
+0

我真的很喜歡這個答案,瞭解有關該功能的PHP文件,但無法理解它100%時,第一個參數是對我來說有點混亂,幸虧雖然:) – Vartox

+0

我在不太好PHP但'%'應該啓動格式字符串, –

+0

我不太擅長PHP。從右到左應該是:這是一個寬度爲2個字符的字符串;如果只有一個字符(即<10),則填充/填充「0」。 '%'開始格式字符串。我認爲格式類似於C函數sprintf:[link](http://www.tutorialspoint.com/c_standard_library/c_function_sprintf.htm)希望有幫助。 –

1

你的方式幾乎是最簡單的選擇,但你不需要檢查月的大小,str_pad爲你做。

$month = "00"; // represents January 
$month = (int) $month; 
$month += 1; 
$month = str_pad($month, 2, "0", STR_PAD_LEFT); 
0

如何:

$month = "00"; // represents January 

// just increment the string value 
// comment out the to display the different months 
$month++; 
$month++; 
$month++; 
$month++; 
$month++; 
$month++; 
$month++; 
$month++; 
$month++; 
$month++; 
$month++; 
$month++; 

// Month = 13 when un-commenting, but should return 01 
// $month++; 


$month = ($month > 12) ? "01": str_pad($month, 2, "0", STR_PAD_LEFT); 

echo "Month: {$month}\n"; 
0

不知道這是你的意思:

switch($monthString) 
{ 
case "January": $monthInt = "00"; 
break; 
case "Febuary": $monthInt = "01"; 
break; 
case "March": $monthInt = "02"; 
break; 
case "April": $monthInt = "03"; 
break; 
... 
}