Pregunta

¿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 y el campo por el que quiero ordenar.Miré la clasificación de matrices multidimensionales y podría haber algo útil allí, pero no veo nada elegante u obvio.

¿Fue útil?

Solución

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 ordenarse por sí solos, consulte el ejemplo 3 aquí: http://php.net/usort

Otros consejos

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/cierres anónimos.Podría resultarle útil revisar los documentos php al respecto.

Incluso puedes incorporar el comportamiento de clasificación en la clase que estás clasificando, 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 );

Para esa función de comparación, puedes simplemente hacer:

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

La función usort (http://uk.php.net/manual/en/function.usort.php) es tu amigo.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 se perderán las claves de la matriz.

Podrías usar el usort() función y cree 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;
    }
}

Dependiendo del problema que esté intentando resolver, es posible que también le resulten útiles las interfaces SPL.Por ejemplo, implementar la interfaz ArrayAccess le permitiría acceder a su clase como una matriz.Además, implementar la interfaz SeekableIterator le permitirá recorrer su objeto como si fuera una matriz.De esta manera, 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:

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;

}

por ejemplo =>

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

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

Puedes tener casi el mismo código que publicaste ordenado función 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'));

Si desea explorar el (aterrador) alcance completo de las funciones de estilo lambda en PHP, consulte:http://docs.php.net/manual/en/function.create-function.php

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top