Domanda

I'm trying to make a select list of prices in my system. The prices are stored as integers. I'm able to get the lowest price and highest price but I want to display them in a select list. I don't want the select list to increment slowly but by 100 or 10,000 or, 100,000 depending on what my starting number is what where i'm at in my incrementation.

For example, say I have these 2 prices:

500000
12345689

I'm trying to increment them by 100,000 Then when I get to 1,000,000 I want to increment by that. It will look something like this:

500000
600000
700000
800000
900000
1000000
2000000

I'm using a custom function and a bit of formatting to get all my prices and get my start price and end price:

$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 ) );
}

Using the same example above, my start price and end price will be:

$price_start = 500000
$price_end   = 20000000

Now it's at the loop where I run into trouble incrementing it by the values I want. I'm trying to use a while loop and determine where I am in my incrementer:

<?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;

?>

I ended up adding in the x variable because I kept running into infinite loop problems but theoretically it should be while($i <= $price_end). Can somebody point me in the right direction on how to get the expected output please? I feel like I'm close but not quite there yet and there's probably a better / faster way to go about it. Any help would be great.

I guess a simplified way of looking at it is:

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

and so forth.

È stato utile?

Soluzione

  1. Get power of 10: log10(1234); // 3.09131
  2. Round down: floor(log10(1234)); // 3
  3. Re-raise as power of 10: pow(10,floor(log10(1234))); // 1000
  4. ???
  5. Profit.

Altri suggerimenti

If someone needs the full solution here it is:

$price = 100; // Starting Price
$priceEnd = 10000; // Ending Price

while($price <= $priceEnd) { 
    echo $price . "<br/>";
    $increase = pow(10,floor(log10($price)));
    $price = $price + $increase;
} 
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top