Sort PHP foreach loop lowest to highest

I have a PHP foreach loop that displays the lowest possible rate on each users profile. How can I sort the foreach loop to display profiles from lowest to highest rate without changing the SQL statement?

$results = DB::query('SELECT users.`id`, rates.`basic`, rates.`standard`, rates.`premium` FROM rates, users WHERE rates.`rate_id` = users.`id`');

foreach($results as $row){
  if($row['basic'] !=""){
     $minrate = $row['basic'];
  }elseif($row['standard'] !=""){
     $minrate = $row['standard'];
  }elseif($row['premium'] !=""){
      $minrate = $row['premium']; 
  }
  <?php echo $minrate ?>
}

2 answers

  • answered 2018-01-13 17:23 Eddie

    The ideal solution for this is to use SQL on sorting results. But if for a certain reason, you cant alter the SQL code. You can:

        $tempArr = array();
        foreach($results as $row){
            if($row['basic'] != ""){
                 $minrate = $row['basic'];
            }elseif($row['standard'] !=""){
                 $minrate = $row['standard'];
            }elseif($row['premium'] !=""){
                  $minrate = $row['premium']; 
            }
    
            //Make the $minrate the key - Will be easy to sort | Make a multi dimensional array, incase duplicate on $minrate
            if ( !isset( $tempArr[ $minrate ] ) ) $tempArr[ $minrate ] = array();
            $tempArr[ $minrate ][] = $row;
        }
    
        //Sort an array by key
        ksort( $tempArr );
    
        //Make Multi dementional array to single array
        $sortedResult = array();
        foreach( $tempArr as $tempArr2 ) {
            foreach( $tempArr2 as $value ) {
                $sortedResult[] = $value;
            }
        }
    
        //$sortedResult <-- As the variable says, It should be sorted
        echo "<pre>";
        print_r( $sortedResult ) ;
        echo "</pre>";
    

  • answered 2018-01-13 17:23 scaisEdge

    seems you have bad data strucs Instead of a relation between user and the user rate you have a relation between user a set of columns for different possible rate

    then you could use case when for filter (and normalize) the set of columns
    and you could obtain the ordered result directly form SQL

       SELECT 
        users.id, 
          case when  rates.basic is not null then 0
               when  rates.standard is not null then 1
               when  rates.premium is not null then 2 
              end as my_rate,
          case when  rates.basic is not null then 'BASIC'
               when  rates.standard is not null then  'STANDARD'
               when  rates.premium is not null then  'PREMIUM'
              end as my_rate_text    
          FROM rates, users WHERE rates.`rate_id` = users.`id`
          ORDER BY  my_rate
          ;