[英]PHP Add Leading Zeros based on query array
I am trying to add leading zeros to all skus in my table. 我试图将前导零添加到表中的所有skus。 I need every sku to have a 3 digit number in front of it.
我需要每个sku前面都有一个3位数字。 For 1-9 skus would be 001$row['sku'], 002$row['sku'], 009$row['sku'], 010$row['sku'], 011$row['sku'],...etc I am using $n=sizeof($row).
对于1-9 skus分别为001 $ row ['sku'],002 $ row ['sku'],009 $ row ['sku'],010 $ row ['sku'],011 $ row ['sku' ],... etc我正在使用$ n = sizeof($ row)。 But every time I echo this out I get 22 skus (which there are about 50) and only returns the first letter of the sku.
但是,每次我回声时,我都会得到22 skus(大约有50),并且只返回sku的第一个字母。 I don't understand how to fix this, I am trying to build an array from my query to determine how many skus there are in order to add leading zeros.
我不知道如何解决此问题,我正在尝试从查询中构建一个数组,以确定要添加前导零的skus有多少。 Any help is much appreciated.
任何帮助深表感谢。
$result = mysql_query("SELECT * FROM temp_table WHERE po='ABCD'");
$row = mysql_fetch_array($result);
for ($i=0, $n=sizeof($row); $i<$n; $i++) {
if ($i < 9) {
$Zeros="00";
}
elseif ($i < 99) {
$Zeros="0";
}
else{
$Zeros="";
}
$num=$i+1;
echo $Zeros.$num. "=" . $row[$i]['sku'] . "`<br />`";
You aren't looping through the resulting data set quite right, or I don't fully understand the situation. 您没有完全正确地浏览生成的数据集,或者我不完全了解这种情况。
Assuming you want to build a three-digit SKU based on each row's SKU, here's a better way: 假设您想基于每一行的SKU构建一个三位数的SKU,这是一种更好的方法:
// query the database
$result = mysql_query("SELECT * FROM temp_table WHERE po='ABCD'");
$count = 0;
// Loop through every row in the data result set
while ( $row = mysql_fetch_assoc( $result ) ){
$count++; // Increment SKU #
// Build integer SKU based on count of item in order and pad with zeros
$this_sku = str_pad( $count, 3, '0', STR_PAD_LEFT);
// Build onto integer SKU based on row data and pad with zeros
$this_sku .= str_pad( $row['sku'], 3, '0', STR_PAD_LEFT);
echo "This product SKU is $this_sku<br/>";
}
You are looking for the str_pad function . 您正在寻找str_pad函数 。
example: 例:
$num = str_pad($input, 4, "0", STR_PAD_LEFT);
最优雅的方法是使用sprintf() http://php.net/manual/en/function.sprintf.php
sprintf(%'0'3d=%d`<br />`, $num, $row[$i]['sku']);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.