sort por ordenar objetos multidimensional fecha asociativo array php arrays sorting

por - sort array php



Ordenar Objeto en PHP (10)

¿Cuál es una forma elegante de ordenar objetos en PHP? Me encantaría lograr algo similar a esto.

$sortedObjectArary = sort($unsortedObjectArray, $Object->weight);

Básicamente especifique la matriz que quiero ordenar así como también el campo en el que quiero ordenar. Analicé la ordenación de matrices multidimensionales y podría haber algo útil allí, pero no veo nada elegante u obvio.


Casi textualmente del manual:

function compare_weights($a, $b) { if($a->weight == $b->weight) { return 0; } return ($a->weight < $b->weight) ? -1 : 1; } usort($unsortedObjectArray, ''compare_weights'');

Si desea que los objetos puedan clasificarse por sí mismos, consulte el ejemplo 3 aquí: http://php.net/usort


Dependiendo del problema que está tratando de resolver, también puede encontrar útiles las interfaces SPL. Por ejemplo, la implementación de la interfaz ArrayAccess le permitiría acceder a su clase como una matriz. Además, la implementación de la interfaz SeekableIterator le permite recorrer su objeto como una matriz. De esta forma, podría ordenar su objeto como si fuera una matriz simple, teniendo control total sobre los valores que devuelve para una clave determinada.

Para más detalles:


Incluso puedes construir el comportamiento de clasificación en la clase que estás ordenando, si quieres ese nivel de control

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


La función de usort ( http://uk.php.net/manual/en/function.usort.php ) es tu amiga. Algo como...

function objectWeightSort($lhs, $rhs) { if ($lhs->weight == $rhs->weight) return 0; if ($lhs->weight > $rhs->weight) return 1; return -1; } usort($unsortedObjectArray, "objectWeightSort");

Tenga en cuenta que cualquier clave de matriz se perderá.


Para esa función de comparación, puedes hacer lo siguiente:

function cmp( $a, $b ) { return $b->weight - $a->weight; }


Para php> = 5.3

function osort(&$array, $prop) { usort($array, function($a, $b) use ($prop) { return $a->$prop > $b->$prop ? 1 : -1; }); }

Tenga en cuenta que esto utiliza funciones anónimas / cierres. Puede encontrar la revisión de los documentos php en ese útil.


Puede tener casi el mismo código que publicó con la función sorted de 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''));


Puede usar la función http://php.net/usort y crear su propia función de comparación.

$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; } }



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

eg =>

$myAscSortedArrayObject=PHPArrayObjectSorter($unsortedarray,$totalMarks,''asc''); $myDescSortedArrayObject=PHPArrayObjectSorter($unsortedarray,$totalMarks,''desc'');