1

Below I have an array that I generate, I need to order each by the 3rd [2] values.

Array:

{
aknox: {
    0: "28",
    1: "39",
    2: "71.79"
    },
    lphillips: {
    0: "81",
    1: "106",
    2: "76.42"
    }
}

Expected result:

{
    lphillips: {
    0: "81",
    1: "106",
    2: "76.42"
    },
    aknox: {
    0: "28",
    1: "39",
    2: "71.79"
    }
}

I have tried the following:

usort($ccstats, function($a, $b) {
   return strcmp($a[2], $b[2]);
});

$ccstats being the array.

This returns the array in ascending order when I tried to make array keys in descending order i.e. "akonx" and "lphillips" get lost and turned into 0 and 1

Any help appreciated

1
  • 1
    use uasort and the inverse of what you have strcmp($b[2], $a[2]); Commented Jul 7, 2017 at 9:15

1 Answer 1

1

To preserve keys use uasort:

uasort($ccstats, function($a, $b) {
   return strcmp($a[2], $b[2]);
});

If you say that you have ascending order but want descending, then just swap arguments in strcmp

uasort($ccstats, function($a, $b) {
   return strcmp($b[2], $a[2]);
});
Sign up to request clarification or add additional context in comments.

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.