簡體   English   中英

在PHP中對對象數組進行排序

[英]Sorting an array of objects in PHP

我想在類中編寫一個靜態方法來對對象數組進行一般排序。

我正在考慮以下方面的東西:

class GenUtils {
  const ASCENDING = 1;
  const DESCENDING = 2;

  protected static alphaSort($value1, $value2, $sort_type=self::DESCENDING){
     $retval = strcasecmp($value1, $value2);
     return ($sort_type == self::DESCENDING) ? $retval : (-1*$retval);
  }

  protected static numericSort($value1, $value2, $sort_type=self::DESCENDING){
    return  $value1 < $value2;
  }

  // Assumption: array is non-empty and homogeneous
  public doSort(array& $object_array, $method_name, $sort_type=self::DESCENDING) {
        if(!empty($object_array) && method_exists($object_array[0],$method_name)) {
          $element = $object_array[0];
          $value = $element->$method_name();
          if(is_string($value)){
            //do string sort (possibly using usort)
          }
          elseif(is_number($value)){
            //do numeric sort (possibly using usort)
          }
        }
  }
}

這只是一個快速的頭腦轉儲-有人可以填寫遺失的部分,或者提出更好的方法來做到這一點?

[編輯]為了明確起見,要排序的對象(在數組中)具有返回字符串(例如getName())或數值(例如getId())的方法。

因此,典型的用例代碼段將如下所示:

GenUtils::doSort($objects,'getName'); // This will do an alphabetic DESC sort using the getName() method

GenUtils::doSort($objects, 'getId', GenUtils::ASCENDING); // This will do a numeric ASC sort using the getId() method

您的示例中的用例(數字和字符串)已經內置在PHP中-檢出sort函數。 除非有更具體的需求,否則我將使用內置函數。

使用usort並定義自己的比較函數以使用對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM