1

i'm Fabio Masino and i'm italian, so my English may be not perfect.

I would like to realize a method for sorting football groups

  • by points (sorted as numbers, in descending order),
  • then by goals scored (sorted as numbers, in descending order),
  • then by name (sorted as strings in ascending order).

For example, if i have this multi-dimensional array:

$group=array(
       array("Juve", 15, 45), // the values are name, points and goals scored
       array("Inter", 21, 40),
       array("Milan", 15, 50)
      );

I would like to have this result:

 $group=array(
           array("Inter", 21, 40),
           array("Milan", 15, 50),
           array("Juve", 15, 45)
          );

Thank you in advance and best regards.

Fabio Masino
  • 69
  • 1
  • 8

4 Answers4

2

Points is the second element of each subarray, right? If so, then do this

function CustomSort($a, $b)
{
    return $a[1] < $b[1] ? -1 : 1;
}

usort($group, 'CustomSort');

If you want to focus on other criteria like names and goals, then just change the numeric array index to the number that represents each criteria in each subarray. For example, sorting names would just be

function NameSort($a, $b)
{
    return $a[0] > $b[0] ? -1 : 1;
}
Lance
  • 4,488
  • 16
  • 49
  • 85
1
$group = array(
    array("Juve", 15, 45), // the values are name, points and goals scored
    array("Inter", 21, 40),
    array("Milan", 15, 50)
);

usort(
    $group,
    function($a, $b) {
        if ($a[1] == $b[1]) {
            if ($a[2] == $b[2]) {
                return ($a[0] < $b[0]) ? -1 : 1;  // by team name (ascending)
            }
            return ($a[2] < $b[2]) ? 1 : -1;  // by goals scored (descending)
        }
        return ($a[1] < $b[1]) ? 1 : -1;  // by points (descending)
    }
);

var_dump($group);
Mark Baker
  • 199,760
  • 28
  • 325
  • 373
1
$group=array(
       array("Juve", 15, 45), // the values are name, points and goals scored
       array("Inter", 21, 40),
       array("Milan", 15, 50)
      );

// Obtain a list of columns
foreach ($group as $key => $row) {
    $team[$key]  = $row[0];
    $point[$key] = $row[1];
    $goal[$key] = $row[2];
}

array_multisort($point, SORT_DESC, $goal, SORT_DESC, $group);

echo "<pre>";
print_r($group);

phpfiddle

skler
  • 2,996
  • 2
  • 12
  • 14
0

sorting function :

Use my custom function to achieve your solution it is working

   function multisort (&$array, $key) {
$valsort=array();
$ret=array();
reset($array);
foreach ($array as $ii => $va) {
    $valsort[$ii]=$va[$key];
}
asort($valsort);
foreach ($valsort as $ii => $va) {
    $ret[$ii]=$array[$ii];
}
$array=$ret;
}

multisort($multiarr,"order");

Hope this will sure help you.

liyakat
  • 11,653
  • 2
  • 38
  • 45