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

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

    [2] => Array
        (
            [0] => xx
            [name] => Adam
            [number] => 16
            [birthday] => 01/12/1979
        )

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

)