} public function age() { return $this->age; } } class UserCollection { protected $users; public function __construct(array $users) { $this->users = $users; } public function sortBy($column) { usort($this->users, function ($userOne, $userTwo) use($column) { return $userOne->{$column}() <=> $userTwo->{$column}(); }); } } $collection = new UserCollection([new User('Jeff', 30), new User('Taylor', 29), new User('Jane', 50), new User('Susie', 10)]); $collection->sortBy('age'); var_dump($collection); $games = ['Mass Effect', 'Super Mario Bros', 'Zelda', 'Fallout', 'Metal Gear']; // sort($games); // alphabat sort usort($games, function ($a, $b) { var_dump('a: ' . $a . ', b: ' . $b); // return $b <=> $a; // -1, 0, 1 return strlen($a) <=> strlen($b); }); var_dump($games);
public function name() { return $this->name; } public function age() { return $this->age; } } class UserCollection { protected $users; public function __construct(array $users) { $this->users = $users; } public function users() { return $this->users; } public function sortBy($method) { usort($this->users, function ($userOne, $userTwo) use($method) { return $userOne->{$method}() <=> $userTwo->{$method}(); }); } } $collection = new UserCollection([new User('jabed', 126), new User('bangali', 36), new User('hasan', 46), new User('babu', 56), new User('md', 66)]); //$collection->sortBy('age'); $collection->sortBy('name'); var_dump($collection->users());