填充数组中的数字

时间:2014-05-28 16:02:31

标签: php arrays

我有以下PHP代码创建A-MTP-1-1,A-MTP-1-2等阵列....

<?php
for ($i = 1; $i <= 3; $i++) {           # Pass 3 as you need three sets
    foreach (range(1, 12) as $val) {    # 1,12 again as per your requirements
        $arr[] = "A-MTP-$i-" . $val;

    }
}
foreach (array_chunk($arr, 4) as $k => $arr1) {    # Loop the array chunks and set a key
    $finarray["ch" . ($k + 1)] = $arr1;
}
extract($finarray);   # Use the extract on that array so you can access each array separately
print_r($ch9);        # For printing the $ch9 as you requested.
?>

我需要数组在单位数字前面有0,所以它会变成A-MTP-01-01,A-MTP-01-02等...但是当它到达时不会有零两位数字。

我如何能够实现我的需要,因为我尝试了以下内容并且没有做出任何改变:

for ($i = 01; $i <= 12; $i++) {           # Pass 3 as you need three sets
    foreach (range(01, 12) as $val) {    # 1,12 again as per your requirements
        $arr[] = "A-MTP-$i-" . $val;

2 个答案:

答案 0 :(得分:4)

PHP&#39; sprintf是你的朋友。

所以这行 $arr[] = "A-MTP-$i-" . $val;

会改为这个 $arr[] = sprintf("A-MTP-%02d-%02d", $i, $val);

答案 1 :(得分:2)

我说你应该使用sprintf,如下所示:

$arr[] = sprintf("A-MTP-%02d-%02d", $i, $val);