일반적으로 객체 배열을 정렬하기 위해 클래스에 정적 메서드를 작성하려고합니다.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)
}
}
}
}
이 그냥 빨리 뇌 덤프 누군가가이 일을 더 나은 방법을 빠진 부분을 작성하거나 제안 할 수 -perharps입니다 :
나는의 라인을 따라 뭔가를해야만 생각하고?
[편집] 그냥 명확히, 객체가 (배열) 정렬되는 문자열 중 하나를 리턴하는 메소드가 (예 getName()) 또는 수치 값 (예 getId())
전형적인 유스 케이스 코드는 그러므로 다음과 같이 somethimng 될 것이다 : 당신의 예에서
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
왜 'natcasesort()'를 쓰지 않으시겠습니까? –