假设以下
例如,
我有2204个对象,一旦它处理了221个对象,我希望它显示10%,然后一旦它处理了441个对象,我希望它显示20%。基本上这样我就可以了解队列的位置。
在php中写这个我有以下内容:
$i = 0;
$total = 2204 // result of getTotal();
foreach (range ($i, $total) as $i ) {
//do some irrelevant processing
if (($i/$total*100)%10 == 0) {
echo number_format(($i/$total*100),0)."% done.\n";
}
}
但是我的结果集不太理想,我得到以下输出:
0% done.
0% done.
0% done.
0% done.
0% done.
0% done.
0% done.
0% done.
0% done.
0% done.
0% done.
0% done.
1% done.
1% done.
1% done.
1% done.
1% done.
1% done.
1% done.
1% done.
1% done.
1% done.
我将如何做到这一点?
答案 0 :(得分:1)
我在这里看到的逻辑还有另一个问题:
由于您通过此列表递增+1,因此不会得到10%,20%。 例如,当我这样做时:
foreach (range ($i, $total) as $i ) {
echo $i/$total."\n";
}
你会看到
0.19555353901996
0.19600725952813
0.1964609800363
0.19691470054446
0.19736842105263
0.1978221415608
0.19827586206897
0.19872958257713
0.1991833030853
0.19963702359347
0.20009074410163
0.2005444646098
0.20099818511797
0.20145190562613
您可能希望在乘以100后将它们舍入并保持一个单独的数组,您将检查是否已显示这些值。
示例程序:
foreach (range ($i, $total) as $i ) {
$val = round($i/$total*100)%10;
$num = number_format(($i/$total*100),0);
if ($val == 0) {
if(!in_array($num, $check)){
$check[] = $num;
echo $num."% done.\n";
}
}
}
?>
答案 1 :(得分:1)
$i = 0;
$total = 2204;
foreach (range ($i, $total) as $i ) {
if ($i % floor($total/100) == 0) {
echo number_format(($i/$total*100),0)."% done.\n";
}
}
如果你只需要每10%(10,20,30 ... 100)而不包括你可以做的0:
$i = 0;
$total = 2204;
foreach (range ($i, $total) as $i ) {
if ($i % floor($total/10) == 0 && $i > 0) {
echo number_format(($i/$total*100),0)."% done.\n";
}
}
答案 2 :(得分:1)
我的2p答案是使用检查变量
<?php
$i = 0;
$total = 2204; // result of getTotal()
$boundary=10;
foreach (range ($i, $total) as $i ) {
//do some irrelevant processing
$ii=intval(($i/$total)*100);
if($ii>=$boundary){
echo $boundary . "% done.\n";
$boundary+=10;
}
}
?>