Fabio Masino
Fabio Masino

Reputation: 67

Sorting a 2d array by multiple columns

I would like to realize a method for sorting football groups

For example, if I have this multidimensional 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)
);

Upvotes: 0

Views: 3669

Answers (4)

M. Foti
M. Foti

Reputation: 3182

$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

Upvotes: 1

Lance
Lance

Reputation: 4820

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

Upvotes: 2

Mark Baker
Mark Baker

Reputation: 212412

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

Upvotes: 1

liyakat
liyakat

Reputation: 11853

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.

Upvotes: 0

Related Questions