1

I'm dying here, any help would be great.

I've got an array that I can sort a-z on the value of a specific key but cannot sort in reverse z-a.

sample of my array which i'd like to sort by ProjectName (z-a):

Array
( 
 [0] => Array
    (
        [count] => 1
        [ProjectName] => bbcjob
        [Postcode] => 53.471922,-2.2996078
        [Sector] => Public

    )

[1] => Array
    (
        [count] => 1
        [ProjectName] => commercial enterprise zone
        [Postcode] => 53.3742081,-1.4926439
        [Sector] => Public

    )

[2] => Array
    (
        [count] => 1
        [ProjectName] => Monkeys eat chips
        [Postcode] => 51.5141492,-0.2271227
        [Sector] => Private

the desired results would be to maintain the entire array key -> value structure but with the order:

Monkeys eat chips
Commericial enterprise zone
bbcjob

I hope this makes sense

4
  • So show us the code you use to sort A-Z, and we'll show you how to change it so it will sort Z-A Commented Nov 3, 2013 at 21:40
  • I used function name_sort($x, $y) { return strcasecmp($x['ProjectName'], $y['ProjectName']); } and ran this through uasort with the array Commented Nov 3, 2013 at 21:51
  • 1
    Just reverse the sign of the returned value: _sort($x, $y) { return -(strcasecmp($x['ProjectName'], $y['ProjectName'])); } or reverse the order of the arguments: _sort($y, $x) { return strcasecmp($x['ProjectName'], $y['ProjectName']); } Commented Nov 3, 2013 at 21:55
  • Cheers Mark, can't believe i didn't think of that. Defo a case of staring at a problem too long. :) Commented Nov 3, 2013 at 22:02

1 Answer 1

3

This is a job for usort which lets you define a function to do your comparison and then sort the array based on that.

function cmp($a, $b)
{
    return strcmp($b["ProjectName"], $a["ProjectName"]);
}

usort($yourArray, "cmp");

print_r($yourArray);

Edit: based on your comment, you should just reverse the $x and $y in your function to reverse the order of the sorting performed.

function name_sort($x, $y) 
{
    return strcasecmp($y['ProjectName'], $x['ProjectName']); 
}
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.