简体   繁体   English

PHP中的前导零

[英]Leading zeroes in PHP

I would like to present a list from 0 to 59 with the numbers 0 to 9 having a leading zero. 我想提供一个0到59的列表,数字0到9的前导零。 This is my code, but it doesn't work so far. 这是我的代码,但它到目前为止还不起作用。 What is the solution? 解决办法是什么?

for ($i=0; $i<60; $i++){
    if ($i< 10){      
        sprintf("%0d",$i);
    }
    array_push($this->minutes, $i);
}

Using %02d is much shorter and will pad the string only when necessary: 使用%02d要短得多,只在必要时填充字符串:

for($i=0; $i<60; $i++){
   array_push($this->minutes,sprintf("%02d",$i));
}

You are not assigning the result of sprintf to any variable. 您没有将sprintf的结果分配给任何变量。

Try 尝试

$padded = sprintf("%0d", $i);
array_push($this->minutes, $padded); 

Note that sprintf does not do anything to $i . 请注意,sprintf对$i没有任何作用。 It just generates a string using $i but does not modify it. 它只是使用$i生成一个字符串,但不会修改它。

EDIT: also, if you use %02d you do not need the if 编辑:另外,如果您使用%02d ,则不需要if

Try this... 试试这个...

for ($i = 0; $i < 60; $i++) {
    if ($i < 10) {
        array_push($this->minutes, sprintf("%0d", $i));
    }
    array_push($this->minutes, $i);
}

You are ignoring the returned value of sprintf, instead of pushing it into your array... 你忽略了sprintf的返回值,而不是把它推入你的数组......

important : The method you are using will result in some items in your array being strings, and some being integers. important :您使用的方法将导致数组中的某些项为字符串,有些是整数。 This might not matter, but might bite you on the arse if you are not expecting it... 这可能没关系,但如果你不期待它可能会咬你的屁股......

Use str_pad : 使用str_pad

for($i=0; $i<60; $i++){
    str_pad($i, 2, "0", STR_PAD_LEFT)
}

I like the offered solutions, but I wanted to do it without deliberate for / foreach loops. 我喜欢提供的解决方案,但我想这样做无需刻意for / foreach循环。 So, here are three solutions (subtle variations): 所以,这里有三个解决方案(细微变化):

Using array_map() with a designed callback function 使用带有设计回调函数的array_map()

$array = array_map(custom_sprintf, range(0,59));
//print_r($array);

function custom_sprintf($s) {
    return sprintf("%02d", $s);
}

Using array_walk() with an inline create_function() call 使用带有内联create_function()调用的array_walk()

$array = range(0,59);
array_walk($array, create_function('&$v', '$v = sprintf("%02d", $v);'));
// print_r($array);

Using array_map() and create_function() for a little code golf magic 使用array_map()和create_function()获得一点代码高尔夫魔法

$array = array_map(create_function('&$v', 'return sprintf("%02d", $v);'), range(0,59));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM