PHP nesnelerin bir dizi sıralama

2 Cevap

Ben nesnelerin jenerik tür bir dizi için bir sınıfta bir statik bir yöntem yazmak istiyorum.

Ben çizgisinde somthing düşünüyorum:

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)
          }
        }
  }
}

Bu sadece hızlı bir beyin dökümü-perharps birisi eksik parçaları doldurmak, ya da bunu yapmanın daha iyi bir yol önerebilir mi?

[Edit] Just to clarify, the objects to be sorted (in the array), have methods which return either a string (e.g. getName()) or a numeric value (e.g. getId())

Tipik bir usecase kod parçacığı bu nedenle bu gibi somethimng olacaktır:

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

2 Cevap

Sizin örnekte (sayısal ve string) kullanım durumları zaten PHP için inşa edilmiştir - sort fonksiyonu kontrol edin. Ben daha özel ihtiyaçları vardı sürece ben yerleşik işlevini kullanabilirsiniz.