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"
  }
3
  • What's your criteria for the best 5 person ? Commented Jan 29, 2014 at 6:42
  • Duplicate: stackoverflow.com/questions/2699086/… Commented Jan 29, 2014 at 6:44
  • The best five time @user007 Commented Jan 29, 2014 at 6:51

1 Answer 1

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");
?>
Sign up to request clarification or add additional context in comments.

2 Comments

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 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;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.