1/**
2 * A generic PHP sorting algorithm that uses `usort` and `strcmp`.
3 * `usort` — Sort an array by values using a user-defined comparison function.
4 * `strcmp` — Returns < 0 if param 1 is less than param 2; > 0 if param 1 is greater than param 2, and 0 if they are equal.
5 */
6$questions = [
7 { id: 1, ordinal: 55 },
8 { id: 2, ordinal: 67 },
9 { id: 3, ordinal: 32 },
10];
11
12function sortByOrdinal($param1, $param2) {
13 return strcmp($param1->ordinal, $param2->ordinal);
14}
15
16/* `usort` alters an existing array. */
17usort($questions, "sortByOrdinal");
18
19/**
20 * $questions = [
21 * { id: 3, ordinal: 32 },
22 * { id: 1, ordinal: 55 },
23 * { id: 2, ordinal: 67 },
24 * ];
25 */
1<?php
2class Person {
3 var $first_name;
4 var $last_name;
5
6 function __construct( $fn, $ln ) {
7 $this->first_name = $fn;
8 $this->last_name = $ln;
9 }
10
11 public function get_first_name() {
12 return $this->first_name;
13 }
14
15 public function get_last_name() {
16 return $this->last_name;
17 }
18}
19
20$rob = new Person( 'Rob', 'Casabona' );
21$joe = new Person( 'Joe', 'Casabona' );
22$erin = new Person( 'Erin', 'Casabona' );
23$steve = new Person( 'Steve', 'Wozniack' );
24$bill = new Person( 'Bill', 'Gates' );
25$walt = new Person( 'Walt', 'Disney' );
26$bob = new Person( 'Bob', 'Iger' );
27
28$people = array( $rob, $joe, $erin, $steve, $bill, $walt, $bob );
29
30//The sorting
31usort($people, function($a, $b){
32 return [$a->get_last_name(), $a->get_first_name()] <=> [$b->get_last_name(), $b->get_first_name()];
33});
34
35?>
36
37<pre>
38 <?php print_r($people);?>
39</pre>