开发者

Sorting an array of objects in PHP

I want to write a static method in a class to generically sort an array of objects.

I am thinking of somthing along the lines of:

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

This is just a quick brain dump -perharps someone can fill in the missing pieces, or suggest a better way of doing this?

[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())

A typical usecase code snippet would therefore be somethimng like this:

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


The use cases (numeric and string) in your example are already built in to PHP - Check out the sort function. I would use the built-in function unless I had more specific needs.


Use usort and define your own comparison function to work with your objects.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜