문제
PHP에서 물체를 정렬하는 우아한 방법은 무엇입니까? 나는 이와 비슷한 것을 성취하고 싶습니다.
$sortedObjectArary = sort($unsortedObjectArray, $Object->weight);
기본적으로 정렬하고 싶은 배열과 정렬하고 싶은 필드를 지정합니다. 나는 다차원 배열 분류를 조사하고 거기에 유용한 것이있을 수 있지만 우아하거나 명백한 것은 보이지 않습니다.
해결책
매뉴얼의 거의 구두 :
function compare_weights($a, $b) {
if($a->weight == $b->weight) {
return 0;
}
return ($a->weight < $b->weight) ? -1 : 1;
}
usort($unsortedObjectArray, 'compare_weights');
객체가 스스로 정렬 할 수 있으려면 예제 3을 참조하십시오. http://php.net/usort
다른 팁
php> = 5.3의 경우
function osort(&$array, $prop)
{
usort($array, function($a, $b) use ($prop) {
return $a->$prop > $b->$prop ? 1 : -1;
});
}
이것은 익명의 기능 / 클로저를 사용합니다. 유용한 것에 대해 PHP 문서를 검토 할 수 있습니다.
해당 수준의 제어를 원한다면 정렬 동작을 분류하는 클래스에 구축 할 수도 있습니다.
class thingy
{
public $prop1;
public $prop2;
static $sortKey;
public function __construct( $prop1, $prop2 )
{
$this->prop1 = $prop1;
$this->prop2 = $prop2;
}
public static function sorter( $a, $b )
{
return strcasecmp( $a->{self::$sortKey}, $b->{self::$sortKey} );
}
public static function sortByProp( &$collection, $prop )
{
self::$sortKey = $prop;
usort( $collection, array( __CLASS__, 'sorter' ) );
}
}
$thingies = array(
new thingy( 'red', 'blue' )
, new thingy( 'apple', 'orange' )
, new thingy( 'black', 'white' )
, new thingy( 'democrat', 'republican' )
);
print_r( $thingies );
thingy::sortByProp( $thingies, 'prop1' );
print_r( $thingies );
thingy::sortByProp( $thingies, 'prop2' );
print_r( $thingies );
그 비교 함수의 경우, 당신은 그냥 할 수 있습니다 :
function cmp( $a, $b )
{
return $b->weight - $a->weight;
}
USORT 함수 (http://uk.php.net/manual/en/function.usort.php) 당신의 친구입니다. ... 같은 ...
function objectWeightSort($lhs, $rhs)
{
if ($lhs->weight == $rhs->weight)
return 0;
if ($lhs->weight > $rhs->weight)
return 1;
return -1;
}
usort($unsortedObjectArray, "objectWeightSort");
모든 배열 키는 손실됩니다.
당신은 사용할 수 있습니다 usort () 기능하고 자신만의 비교 기능을 만드십시오.
$sortedObjectArray = usort($unsortedObjectArray, 'sort_by_weight');
function sort_by_weight($a, $b) {
if ($a->weight == $b->weight) {
return 0;
} else if ($a->weight < $b->weight) {
return -1;
} else {
return 1;
}
}
해결하려는 문제에 따라 SPL 인터페이스가 유용 할 수도 있습니다. 예를 들어, ArrayAccess 인터페이스를 구현하면 배열처럼 클래스에 액세스 할 수 있습니다. 또한 SeekableIterator 인터페이스를 구현하면 배열처럼 객체를 통과 할 수 있습니다. 이렇게하면 간단한 배열 인 것처럼 객체를 정렬 할 수 있으며 주어진 키에 대해 반환하는 값을 완전히 제어 할 수 있습니다.
자세한 사항은:
function PHPArrayObjectSorter($array,$sortBy,$direction='asc')
{
$sortedArray=array();
$tmpArray=array();
foreach($this->$array as $obj)
{
$tmpArray[]=$obj->$sortBy;
}
if($direction=='asc'){
asort($tmpArray);
}else{
arsort($tmpArray);
}
foreach($tmpArray as $k=>$tmp){
$sortedArray[]=$array[$k];
}
return $sortedArray;
}
예 :>
$myAscSortedArrayObject=PHPArrayObjectSorter($unsortedarray,$totalMarks,'asc');
$myDescSortedArrayObject=PHPArrayObjectSorter($unsortedarray,$totalMarks,'desc');
당신은 당신이 게시 한 것과 거의 동일한 코드를 가질 수 있습니다. 정렬 기능 NSPL:
use function \nspl\a\sorted;
use function \nspl\op\propertyGetter;
use function \nspl\op\methodCaller;
// Sort by property value
$sortedByWeight = sorted($objects, propertyGetter('weight'));
// Or sort by result of method call
$sortedByWeight = sorted($objects, methodCaller('getWeight'));
PHP의 Lambda 스타일 기능의 전체 (끔찍한) 범위를 탐색하려면 다음을 참조하십시오.http://docs.php.net/manual/en/function.create-function.php