How to create Price Range dynamically with PHP

前端 未结 4 1738
孤街浪徒
孤街浪徒 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条回答
  •  庸人自扰
    2021-01-13 05:46

    I Created this function based on my $array element of my question.

    If this is a good aproach of my question please make some comments for like pointing my mistakes.

    http://laravel.io/bin/VLJn this is the output.

    private function createRange($array){
        sort($array);
    
        //Setting range limits.
        //Check if array has 5 digit number.
        $countDigitedNumbers = preg_grep('/\d{5}/',$array);
        if(count($countDigitedNumbers) > 3){
            $rangeLimits = array(0,1000,2500,5000,10000,15000,20000,25000);
        }else{
            $rangeLimits = array(0,50,250,500,1000,1500,2000,2500);
        }
        $ranges = array();
    
        for($i = 0; $i < count($rangeLimits); $i++){
            if($i == count($rangeLimits)-1){
                break;
            }
            $lowLimit = $rangeLimits[$i];
            $highLimit = $rangeLimits[$i+1];
    
            $ranges[$i]['ranges']['min'] = $lowLimit;
            $ranges[$i]['ranges']['max'] = $highLimit;
    
            foreach($array as $perPrice){
                if($perPrice >= $lowLimit && $perPrice < $highLimit){
                    $ranges[$i]['values'][] = $perPrice;
                }
            }
        }
        return $ranges;
    }
    

提交回复
热议问题