How to create Price Range dynamically with PHP

前端 未结 4 1736
孤街浪徒
孤街浪徒 2021-01-13 05:36

How can I create Price Ranges from price array? Let\'s say I have this array which holds prices:

  Array ( [0] => 500 [1] => 500 [2] => 520 [3] =&g         


        
4条回答
  •  梦毁少年i
    2021-01-13 05:52

    Personally, I would go and define an array (in a config or directly) with the needed ranges, since you may be selling metal screws, worth 0.01$, and at the same time a machine making metal screws, worth 1000$ (for example). This way you have control of all possible price ranges. Going with dynamic price factor could work, but could also go wrong if you suddenly receive an item worth 20000$, and I doubt you will have so many ranges that you would not be able to define them manually. (Feel free pull out the forks and torches here)

    Here's an example. Let's say you have an array of prices. You define your ranges like this:

    $prices = array(1, 5, 10, 25, 500, 100);
    $price_ranges = array(250 => array(), 100 => array(), 10 => array(), 1 => array());
    // edit to your liking
    

    Then you can cycle over all available prices, compare them to the available ranges, starting from the top and go to the bottom. If it fits, it sits.

    foreach ($prices as $price) {
        foreach ($price_ranges as $price_range_key => &$price_range_array) {
            if ($price >= $price_range_key) {
                $price_range_array[] = $price;
                break;
            }
        }
    }
    

    This will produce a nice array with each range (as a key) containing your prices.

    var_dump($price_ranges);
    array(4) {
      [250] =>
      array(1) {
        [0] =>
        int(500)
      }
      [100] =>
      array(1) {
        [0] =>
        int(100)
      }
      [10] =>
      array(2) {
        [0] =>
        int(10)
        [1] =>
        int(25)
      }
      [1] =>
      array(2) {
        [0] =>
        int(1)
        [1] =>
        int(5)
      }
    }
    

    I'm sure you can figure how to get the number of items in each one and display them accordingly. Usually you'll mark the last item as 250+ or something similar.

    Cheers.

提交回复
热议问题