PHP - 使用前导零生成数字,从100开始

时间:2011-11-21 18:47:59

标签: php numbers

我希望有一个函数来生成从" 000100"开始的数字。

现在我有以下功能,允许我生成带前导零的数字。

如何修改它以满足我的需求?

function lz( $aNumber, $intPart, $floatPart=NULL, $dec_point=NULL, $thousands_sep=NULL) 
{     
    $formattedNumber = $aNumber;
    if (!is_null($floatPart)) 
    {  
        $formattedNumber = number_format($formattedNumber, $floatPart, $dec_point, $thousands_sep);
    }

    $formattedNumber = str_repeat("0",($intPart + -1 - floor(log10($formattedNumber)))).$formattedNumber;
    return $formattedNumber;
}

示例:已下达新订单,订单ID为" 19"。最终订单号必须是000119。

谢谢!

4 个答案:

答案 0 :(得分:9)

为什么不使用单个printf

printf("%06d",$number); 

See it

使用的格式说明符是:

% - Marks the beginning of the format specifier
0 - Ensures zero filling if number being printed has fewer digits
6 - Number of digits reserved
d - We are printing an integer

修改

从您的编辑看起来您希望在格式化之前将100添加到输入。如果是这样,你可以这样做:

printf("%06d",$number+100); 

答案 1 :(得分:3)

只需使用str_pad

<?php
    for($i = 100; $i < 115; $i++)
        echo str_pad($i, 6, '0', STR_PAD_LEFT) . '<br>';
?>

http://codepad.viper-7.com/cI9DTO

答案 2 :(得分:0)

$arrayVar = Array();
for($i=100;$i<200;$i++){
$arrayVar[$i] = "000" . $i;
}
foreach($arrayVar as $num){
echo $num . "<br>";
}

基本上只是将0添加到数组中变量的开头,第二部分吐出唯一数字。

答案 3 :(得分:0)

我想知道哪个更快:

sprintf("%06d",$loops);

或者

str_pad($i, 6, '0', STR_PAD_LEFT)

两者之间的差异是微不足道的。 sprintf的速度始终高于str_pad,但通常只有150微秒左右。

Ref: Loops: 10,000    Time: 0.00033807754516602
Time Loop 1: Loops: 10,000 Time: 0.0026688575744629  Time per loop: 0.000000267
Time Loop 2: Loops: 10,000 Time: 0.0040788650512695  Time per loop: 0.000000408

Difference per loop: 0.000 000 141

Ratio Loop2/Loop1: 1.5283187421833
Ratio Loop1/Loop2: 0.65431377133505

我的基准代码:

当基准测试的代码在比循环本身更短的时间内运行时,循环时间将显着影响结果。所以我使用参考循环从测试循环中减去循环时间。

我使用了10,000次迭代的循环。

$saveLoops = 10000;

参考循环:

$loops = $saveLoops;
$t = microtime(true);
while ($loops > 0) {
  $loops--;
}
$refTime = microtime(true) - $t;
echo "Ref: Loops: $saveLoops Time: $refTime\n";

LOOP 1

$loops = $saveLoops;
$t = microtime(true);
while ($loops > 0) {
  $loops--;
  $n = sprintf("%06d",$loops); 

}

$t = microtime(true) - $t - $refTime;
$time['End1'] =  $t;
$t1 = $t/$saveLoops;
echo "Time Loop 1: Loops: " . number_format($saveLoops) . " Time: $t  Time per loop: " . number_format($t1,9) . "\n";

LOOP 2

$loops = $saveLoops;
$t = microtime(true);
while ($loops > 0) {
  $loops--;
  $n = str_pad($loops, 6, '0', STR_PAD_LEFT);
}
$t = microtime(true) - $t - $refTime;
$time['End2'] =  $t;
$t2 = $t/$saveLoops;
echo "Time Loop 2: Loops: " . number_format($saveLoops) . " Time: $t  Time per loop: " . number_format($t2,9) . "\n";

计算时间

$dif = abs($t2 - $t1);
$diff = number_format($dif,9);

$diff = substr($diff,0,5) . ' ' . substr($diff,5,3). ' ' . substr($diff,8,3);

echo "\nDifference per loop: $diff\n";
echo "\nRatio Loop2/Loop1: " . ($time['End2'] / $time['End1']);
echo "\nRatio Loop1/Loop2: " . ($time['End1'] / $time['End2']);