Domanda

Qual è un modo elegante per ordinare gli oggetti in PHP? Mi piacerebbe realizzare qualcosa di simile a questo.

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

Specifica in pratica l'array che voglio ordinare e il campo su cui voglio ordinare. Ho esaminato l'ordinamento di array multidimensionale e potrebbe esserci qualcosa di utile lì, ma non vedo nulla di elegante o ovvio.

È stato utile?

Soluzione

Quasi letteralmente dal manuale:

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

usort($unsortedObjectArray, 'compare_weights');

Se vuoi che gli oggetti siano in grado di ordinare da soli, vedi l'esempio 3 qui: http://php.net/usort

Altri suggerimenti

Per php > = 5.3

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

Nota che utilizza funzioni / chiusure anonime. Potrebbe essere utile rivedere i documenti php su questo.

Puoi persino incorporare il comportamento di ordinamento nella classe che stai ordinando, se vuoi quel livello di controllo

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

Per quella funzione di confronto, puoi semplicemente fare:

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

La funzione usort ( http://uk.php.net/manual /en/function.usort.php ) è tuo amico. Qualcosa come ...

function objectWeightSort($lhs, $rhs)
{
   if ($lhs->weight == $rhs->weight)
     return 0;

   if ($lhs->weight > $rhs->weight)
     return 1;

   return -1;
}

usort($unsortedObjectArray, "objectWeightSort");

Notare che eventuali chiavi dell'array andranno perse.

Puoi utilizzare la usort () e creare la tua funzione di confronto.

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

A seconda del problema che stai cercando di risolvere, potresti trovare utili anche le interfacce SPL. Ad esempio, l'implementazione dell'interfaccia ArrayAccess ti consentirebbe di accedere alla tua classe come un array. Inoltre, l'implementazione dell'interfaccia SeekableIterator ti permetterebbe di scorrere il tuo oggetto come un array. In questo modo puoi ordinare il tuo oggetto come se fosse un semplice array, avendo il pieno controllo sui valori che restituisce per una determinata chiave.

Per maggiori dettagli:

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;

}

ad esempio = >

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

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

Puoi avere quasi lo stesso codice che hai pubblicato con ordinata da 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'));

Se vuoi esplorare l'estensione completa (terrificante) delle funzioni di stile lambda in PHP, vedi: http://docs.php.net/manual/en/function. creare-function.php

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top