Sorting arrays by date

后端 未结 3 2110
梦毁少年i
梦毁少年i 2021-01-28 11:36

I\'ve got a question. I\'m building an array by getting data from mysql and merging three query results in one array.

I put data to array like this:

whil         


        
3条回答
  •  余生分开走
    2021-01-28 12:25

    You probably should use UNION when selecting and not trying to sort arrays on your own. Anyway if you have to may use usort like this:

    function cmp( $a, $b){
      if( !($a instanceOf stdClass) && !($b instanceOf stdClass)){
        return 0;
      }
    
      // Check object
      if(  !($a instanceOf stdClass)){
        return -1;
      }
      if(  !($b instanceOf stdClass)){
        return 1;
      }
    
      $aVal = NULL;
      if( isset( $a->added)){
        $aVal = $a->added;
      } elseif( isset( $a->added_type_2)){
        $aVal = $a->added_type_2;
      } ...
    
      // The same for b
      if( ($aVal == NULL) && ($bVal == NULL)){
        return 0;
      }
    
      if( $aVal == NULL){
        return -1;
      }
    
      if( $bVal == NULL){
        return 1;
      }
    
      if( $aVal == $bVal){
        return 0;
      }
    
      return ($aVal > $bVal) ? 1 : -1;
    
    }
    
    usort( $array, 'cmp');
    

    As you may see the condition how to compare object may get complex when making sure they have correct types and correct values. When selecting mysql columns you should use at least SELECT added_type_2 AS added to have column names more compact and conditions simpler.

提交回复
热议问题