1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
|
class sort
{
public $sorts = array();
public $currentSorts;
public $data = array();
public function __construct( $data , $key)
{
$this->sorts = $key;
$this->currentSorts = reset( $this->sorts );
$this->data = $data;
}
public function sort()
{
usort( $this->data , array($this, 'compare') );
return $this->data;
}
public function compare( $a , $b )
{
if ( $a[$this->currentSorts] == $b[$this->currentSorts] )
{
$this->currentSorts = next( $this->sorts );
return $this->sort_n($a , $b);
}
return ($a[$this->currentSorts] < $b[$this->currentSorts]) ? -1 : 1;
}
public function sort_n( $a , $b)
{
if ( $this->currentSorts !== false )
{
if ( $a[$this->currentSorts] == $b[$this->currentSorts] )
{
$this->currentSorts = next( $this->sorts );
$return = $this->sort_n($a , $b);
}
else
{
$return = ($a[$this->currentSorts] < $b[$this->currentSorts]) ? -1 : 1;
}
}
else
{
$this->currentSorts = end( $this->sorts );
return false;
}
$this->currentSorts = prev( $this->sorts );
return $return;
}
}
$tab =
array(
array( 'id' => 1,'age' => 22 , 'taille' => 333 , 'nom' => 1),
array( 'id' => 2,'age' => 22 , 'taille' => 222 ,'nom' => 2),
array( 'id' => 3,'age' => 21 , 'taille' => 222 ,'nom' => 3),
array( 'id' => 4,'age' => 21 , 'taille' => 223 ,'nom' => 6),
array( 'id' => 5,'age' => 21 , 'taille' => 223 ,'nom' => 7),
array( 'id' => 6,'age' => 21 , 'taille' => 223 ,'nom' => 6),
array( 'id' => 7,'age' => 21 , 'taille' => 223 ,'nom' => 4),
array( 'id' => 8,'age' => 22 , 'taille' => 222 ,'nom' => 1)
);
$sort = new sort( $tab , array( 'age' , 'taille' , 'nom' ) );
$resultat = $sort->sort();
print_r( $resultat); |
Partager