0

I'm trying to sort a two dimensions array, and I have no idea where to start. I looked at array_multisort, but I don't really found a good solution with this sorting.

I need to sort by time, each time are associate with a race. I need to find who are the best 5 person so the best time.

My array looks like this:

 [0]=>
  array(2) {
    [0]=>
    string(15) "Beaumier Mélina"
    [1]=>
    string(7) "1:29.30"
  }
  [1]=>
  array(2) {
    [0]=>
    string(14) "Frizzle Émilie"
    [2]=>
    string(7) "1:47.96"
  }
  [2]=>
  array(3) {
    [0]=>
    string(18) "Morissette Camélia"
    [2]=>
    string(7) "1:50.26"
    [1]=>
    string(7) "1:50.97"
  }

1 Answers1

1

You can use usort. You give it a callback function and compare each index of the array. Since you make the callback function you can compare by the time for each index in the array.

http://php.net/usort

From the above documentation:

<?php
function cmp($a, $b)
{
    return strcmp($a["fruit"], $b["fruit"]);
}

$fruits[0]["fruit"] = "lemons";
$fruits[1]["fruit"] = "apples";
$fruits[2]["fruit"] = "grapes";

usort($fruits, "cmp");
?>
Jasper
  • 75,717
  • 14
  • 151
  • 146
  • I don't find how I can do my sort with this type of sort. I'm not a master in sorting. Can you gave me a short example of how your start would ? So I repeat the goal, sort the times ascending for find the best 5 persons. The best five persons will be the persons they have the five best times so on the top. @Jasper – alexandcote Jan 29 '14 at 07:13
  • @Alexandcote The way `usort` works is: a reference to a function is passed in along with your array. The `usort` function then runs the function for every index in your array. When you `return -1` then the `$a` index is moved to a lower index and when you `return 1` then the `$a` index is moved to a higher index. When you `return 0` nothing is changed. In the above example `strcmp` is used to determine which way the index should be moved. Note that `$a` and `$b` are two indexes of the array. E.g. `if ($a['time'] < $b['time']) {return -1} else if ($a['time'] > $b['time']) {return 1}return 0;` – Jasper Jan 29 '14 at 17:23