fork download
  1. <?php
  2.  
  3. $data = [
  4. ['word' => 'foo'],
  5. ['word' => 'BAR'],
  6. ['word' => 'FOO'],
  7. ['word' => 'bar'],
  8. ];
  9.  
  10. usort($data, make_comparer(['word', SORT_ASC, 'strtolower']));
  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. }
Success #stdin #stdout 0.01s 20520KB
stdin
Standard input is empty
stdout
Array
(
    [0] => Array
        (
            [word] => bar
        )

    [1] => Array
        (
            [word] => BAR
        )

    [2] => Array
        (
            [word] => foo
        )

    [3] => Array
        (
            [word] => FOO
        )

)