fork(29) download
  1. <?php
  2.  
  3. $data = array(
  4. array('zz', 'name' => 'Jack', 'number' => 22, 'birthday' => '12/03/1980'),
  5. array('xx', 'name' => 'Adam', 'number' => 16, 'birthday' => '01/12/1979'),
  6. array('aa', 'name' => 'Paul', 'number' => 16, 'birthday' => '03/11/1987'),
  7. array('cc', 'name' => 'Helen', 'number' => 44, 'birthday' => '24/06/1967'),
  8. );
  9.  
  10. usort($data, make_comparer('name'));
  11. print_r($data);
  12.  
  13.  
  14. function make_comparer() {
  15. // Normalize criteria up front so that the comparer finds everything tidy
  16. $criteria = func_get_args();
  17. foreach ($criteria as $index => $criterion) {
  18. $criteria[$index] = is_array($criterion)
  19. ? array_pad($criterion, 3, null)
  20. : array($criterion, SORT_ASC, null);
  21. }
  22.  
  23. return function($first, $second) use ($criteria) {
  24. foreach ($criteria as $criterion) {
  25. // How will we compare this round?
  26. list($column, $sortOrder, $projection) = $criterion;
  27. $sortOrder = $sortOrder === SORT_DESC ? -1 : 1;
  28.  
  29. // If a projection was defined project the values now
  30. if ($projection) {
  31. $lhs = call_user_func($projection, $first[$column]);
  32. $rhs = call_user_func($projection, $second[$column]);
  33. }
  34. else {
  35. $lhs = $first[$column];
  36. $rhs = $second[$column];
  37. }
  38.  
  39. // Do the actual comparison; do not return if equal
  40. if ($lhs < $rhs) {
  41. return -1 * $sortOrder;
  42. }
  43. else if ($lhs > $rhs) {
  44. return 1 * $sortOrder;
  45. }
  46. }
  47.  
  48. return 0; // tiebreakers exhausted, so $first == $second
  49. };
  50. }
  51.  
Success #stdin #stdout 0.01s 20520KB
stdin
Standard input is empty
stdout
Array
(
    [0] => Array
        (
            [0] => xx
            [name] => Adam
            [number] => 16
            [birthday] => 01/12/1979
        )

    [1] => Array
        (
            [0] => cc
            [name] => Helen
            [number] => 44
            [birthday] => 24/06/1967
        )

    [2] => Array
        (
            [0] => zz
            [name] => Jack
            [number] => 22
            [birthday] => 12/03/1980
        )

    [3] => Array
        (
            [0] => aa
            [name] => Paul
            [number] => 16
            [birthday] => 03/11/1987
        )

)