如何格式化PHP中0到000的数字?

时间:2016-12-28 16:56:36

标签: php

我需要更改整数的格式。我知道需要应用sprintf功能,但不确定如何正确应用。

格式为0到000.

例如1到001& 19至019。

我从网址获取商品代码。

$catCode=isset($_GET["cat"]) ? $_GET["cat"] : "ac";
$itemCode=isset($_GET["itemCode"]) ? $_GET["itemCode"] : "001";

foreach ($productArr[$catCode] as $imgNumber => $productDetail) {
            array_push($arr, $imgNumber);
            $imgNumber = $arr;
        }

//count the total number of items in the array
        $totalItem = count($arr);
        $prevItem = ($itemCode + $totalItem - 2) % $totalItem + 1;
        $nextItem = $itemCode % $totalItem + 1;

        if ($itemCode > $totalItem || $itemCode < 1) {
            $itemCode = 1;
        }

echo"<a href='http://localhost/collectionDetail.php?cat={$catCode}&itemCode={$prevItem}' ><img src='images/arrow_left.jpg'> </a>";
echo"<a href='http://localhost/collectionDetail.php?cat={$catCode}&itemCode={$nextItem}' ><img src='images/arrow_right.jpg'> </a>";

1 个答案:

答案 0 :(得分:1)

简单,将sprintf连接到.

echo "<a href='http://localhost/collectionDetail.php?cat=".sprintf("%03d",$catCode)."&itemCode=".sprintf("%03d",$prevItem)."' ><img src='images/arrow_left.jpg'> </a>";
echo "<a href='http://localhost/collectionDetail.php?cat=".sprintf("%03d",$catCode)."&itemCode=".sprintf("%03d",$nextItem)."' ><img src='images/arrow_right.jpg'> </a>";