0

I have an array that looks like the following. Background: As you see, this is a table of a tournament. I now want to "sort" that table: The team ("mannschaft") with the most points ("punkte") should be at [0], the second team at [1] and so on. If the points ("punkte") are equal, the team with more goals should be first, etc. If all teams have equal points, equal goals, etc., I want to echo something like "could not calculate winner because points, goals, etc. are equal."

I tried with two for loops to compare one value to each other, but this somehow messes up the order.

Any suggestions would be great.

Array
(
    [0] => Array
        (
            [mannschaft] => 183
            [punkte] => 3
            [tore] => 2
            [gegentore] => 2
            [tordifferenz] => 0
        )

    [1] => Array
        (
            [mannschaft] => 182
            [punkte] => 3
            [tore] => 2
            [gegentore] => 2
            [tordifferenz] => 0
        )

    [2] => Array
        (
            [mannschaft] => 184
            [punkte] => 3
            [tore] => 2
            [gegentore] => 2
            [tordifferenz] => 0
        )

)

Ok so with usort it was easy to order the array.

usort($einzelnes_punkte_arr, "cmp");

function cmp($a, $b){
if ($a["tabelle_punkte"] == $b["tabelle_punkte"] AND $tordifferenz_a == 
    $tordifferenz_b AND $tore_a == $tore_b) {
    echo "$mannschaft_a_string and $mannschaft_b_string are equal<br>";
    return 0;
}else if($punkte_a > $punkte_b){
    return -1;
}else if($tordifferenz_a > $tordifferenz_b){
    return -1;
}else if($tore_a > $tore_b){
    return -1;
}else{
    return 1;
}
}

My problem now: How to return a custom variable when the usort callbacks function is 0? The echo works nice, but I need this "echo" outside the callback.

Michael
  • 13
  • 6
  • https://www.php.net/manual/en/function.usort.php – Manuel Guzman Jul 07 '22 at 22:01
  • Do it in two steps: First, sort the list, using usort or any of the other methods discussed on the linked reference. Then, compare the top two items; if they have different stats, you have a winner, otherwise it's a tie. If you want to say "5 teams are all tied at the top", do the second stage as a loop, but sort the array first before attempting that. – IMSoP Jul 07 '22 at 22:08
  • Sorting with usort was easy, but how should i now compare the items to return a message when the points, goals etc. are all equal? I don't really get what you mean with "compare top two items"? Why would that make sense? – Michael Jul 07 '22 at 23:05

0 Answers0