2012-07-26 26 views
6

將在PHP 0領先

  • 教程1如何使這個
  • 教程21如何使這個
  • 教程2如何使這個
  • 教程3如何使這個

,我需要

  • 教程01如何使這個
  • 教程21如何使這個
  • 教程02如何使這個
  • 教程03如何使這個

這樣我就可以正常訂購。 (當找到單個數字時加上前導0)

什麼是一種php方法轉換?

在此先感謝

筆記,請確保它標識的單個數字的只有第一,然後添加前導零

+0

[ sprintf](http://php.net/manual/en/function.sprintf.php) – Musa 2012-07-26 00:29:06

+0

三位數字呢?當你達到100個教程時,你想讓01成爲001嗎?四位數字呢?等 – Peter 2012-07-26 00:31:23

+0

現在,兩位數字是好的,我沒有看到一個情況下,教程是超過100,謝謝 – msjsam 2012-07-26 00:40:53

回答

4

如果它來自D B,這是做一個SQL查詢的方式:

lpad(yourfield, (select length(max(yourfield)) FROM yourtable),'0') yourfield 

這將讓你在表中的最大值,並放置前導零。

如果它硬編碼(PHP),使用str_pad()

str_pad($yourvar, $numberofzeros, "0", STR_PAD_LEFT); 

這是我做的事在網上PHP編譯一個小例子,和它的作品...

$string = "Tutorial 1 how to"; 

$number = explode(" ", $string); //Divides the string in a array 
$number = $number[1]; //The number is in the position 1 in the array, so this will be number variable 

$str = ""; //The final number 
if($number<10) $str .= "0"; //If the number is below 10, it will add a leading zero 
$str .= $number; //Then, add the number 

$string = str_replace($number, $str, $string); //Then, replace the old number with the new one on the string 

echo $string; 
9

str_pad()

echo str_pad($input, 2, "0", STR_PAD_LEFT); 

sprintf()

echo sprintf("%02d", $input); 
+0

這一個不接受條件「單個數字只」請幫助 – msjsam 2012-07-26 00:38:57