Created
August 25, 2014 19:36
-
-
Save emodric/51d11c8f92ff0a1fc648 to your computer and use it in GitHub Desktop.
Sort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Test | |
{ | |
public $id; | |
public function __construct($id) | |
{ | |
$this->id = $id; | |
} | |
} | |
class Sort | |
{ | |
public $priorities; | |
public $objects; | |
public function __construct() | |
{ | |
$this->priorities = array( 2, 4, 7, 13 ); | |
$this->objects = array( new Test(4), new Test(13), new Test(2), new Test(7) ); | |
} | |
public function doSort() | |
{ | |
usort( $this->objects, array( $this, 'compare' ) ); | |
} | |
public function compare( Test $first, Test $second ) | |
{ | |
$firstPriority = array_search( $first->id, $this->priorities ); | |
$secondPriority = array_search( $second->id, $this->priorities ); | |
if ( $firstPriority == $secondPriority ) | |
{ | |
return 0; | |
} | |
return ( $firstPriority < $secondPriority ) ? -1 : 1; | |
} | |
} | |
$sort = new Sort(); | |
$sort->doSort(); | |
var_dump( $sort->objects ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment