【问题标题】:Increment Price by Hundred, Thousand, Ten-Thousand, etc百、千、万等加价
【发布时间】:2014-06-27 14:00:15
【问题描述】:

我正在尝试在我的系统中制作一个精选的价格列表。价格存储为整数。我能够获得最低价格和最高价格,但我想在选择列表中显示它们。我不希望选择列表缓慢增加,而是增加 100 或 10,000 或 100,000,具体取决于我的起始编号是我在增量中所处的位置。

例如,假设我有这 2 个价格:

500000
12345689

我正在尝试将它们增加 100,000 然后当我达到 1,000,000 时,我想增加它。它看起来像这样:

500000
600000
700000
800000
900000
1000000
2000000

我正在使用自定义函数和一些格式来获取我的所有价格并获取我的起始价格和结束价格:

$prices = my_custom_function();     // Pulls All Prices in a random order
if(!empty($prices)){
    sort($prices);                     // Sort Prices Lowest to Highest
    $price_low  = $prices[0];
    $price_high = $prices[count($prices)-1];

    $price_start = intval( $price_low[0].str_repeat( '0', strlen( $price_low ) - 1 ) );             
    $price_end   = intval( ( $price_high[0] + 1 ).str_repeat( '0', strlen( $price_high ) -1 ) );
}

使用上面的相同示例,我的起始价格和结束价格将是:

$price_start = 500000
$price_end   = 20000000

现在在循环中,我遇到了按我想要的值递增它的麻烦。我正在尝试使用 while 循环并确定我在增量器中的位置:

<?php $i = $price_start; $x = 0; while($x < 10) : ?>
    <option value="<?php echo $i; ?>"><?php echo format_price($i); ?></option>
<?php 

    if(1000 % $i == 0)
        $i+=1000;
    else if(10000 % $i == 0)
        $i+=10000;
    else if(100000 % $i == 0)
        $i+=100000;
    else if(1000000 % $i == 0)
        $i+=1000000;
    else
        $i+=10000000;

    $x++;
    endwhile;

?>

我最终添加了 x 变量,因为我一直遇到无限循环问题,但理论上它应该是 while($i &lt;= $price_end)。有人可以为我指出如何获得预期输出的正确方向吗?我觉得我已经很接近了,但还没有完全到那里,可能有更好/更快的方法来解决它。任何帮助都会很棒。

我想一个简化的看待它的方式是:

1 -> +1
10 -> +10
100 -> +100
1000 -> +1000
10000 -> +10000

等等。

【问题讨论】:

    标签: php loops formatting logic


    【解决方案1】:
    1. 获得 10 的幂:log10(1234); // 3.09131
    2. 向下取整:floor(log10(1234)); // 3
    3. 重新加注为 10 的幂:pow(10,floor(log10(1234))); // 1000
    4. ???
    5. 利润。

    【讨论】:

      【解决方案2】:

      如果有人需要完整的解决方案,那就是:

      $price = 100; // Starting Price
      $priceEnd = 10000; // Ending Price
      
      while($price <= $priceEnd) { 
          echo $price . "<br/>";
          $increase = pow(10,floor(log10($price)));
          $price = $price + $increase;
      } 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-05
        • 1970-01-01
        • 1970-01-01
        • 2021-12-14
        • 1970-01-01
        • 2013-07-06
        相关资源
        最近更新 更多