2

This is an example of an array that I am trying to sort by the key match_points (descending):

Let the array printed below be called $my_arr.

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [109] => 92
                    [match_points] => 50
                )

        )

    [1] => Array
        (
            [0] => Array
                (
                    [16] => 12
                    [match_points] => 62
                )

        )

    [2] => Array
        (
            [0] => Array
                (
                    [80] => 51
                    [match_points] => 63
                )

        )

)

I tried this:

$a = usort($my_arr, 
    function (array $a, array $b) { 
        return $a["match_points"] - $b["match_points"]; 
    }
);

But I am getting this warning message:

Undefined index: match_points

This post did not explicitly show how to sort a 3 dimensional array by a specific key, although the answer can be inferred after reading that post.

Community
  • 1
  • 1
lschlessinger
  • 1,934
  • 3
  • 25
  • 47

2 Answers2

3

The problem is your array is 3 dimensional but your sort is structured for a two dimensional array.

In php 5.3+ you can use usort with a closure

 usort($array, function($a, $b){return $a[0]["match_points"] - $b[0]["match_points"];}); 

Prior to 5.3 you have define a sorter function.

 function compMatchPoints($a, $b) {
      return $a[0]["match_points"] - $b[0]["match_points"];
 }
 usort($array, "compMatchPoints");
Orangepill
  • 24,500
  • 3
  • 42
  • 63
1

Change all the $data variable to your array variable name

 $sortkeys = array();
    foreach ($data as $row) {
        $sortkeys[] = $row[0]['match_points'];
    }

// sort $data according to $sortkeys and use SORT_DESC for descending order

array_multisort($sortKeys,SORT_DESC, $data, SORT_DESC);

echo "<pre>"
print_r($data);
die;
Rohan Varma
  • 101
  • 7