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.

5
  • You have one more array dimension inside each array! Use var_dump to see what you're working with. Commented Jul 22, 2013 at 15:02
  • 1
    does $a[0]["match_points"] and $a[0]["match_points"] help anything? Commented Jul 22, 2013 at 15:04
  • Which part of the error message is/was unclear to you? Commented Jul 22, 2013 at 15:15
  • @hakre the error message itself wasn't unclear. What was unclear was how to fix it. Commented Jul 22, 2013 at 15:19
  • Well I don't understand that. If the error message was clear, why was it unclear to fix it? What specifically was unclear for the fix by that error message? Commented Jul 22, 2013 at 15:42

2 Answers 2

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

Comments

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;

Comments

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.