3

I am creating a search capability for a forum program I'm building. At one point I have an array called searchResults which is numeric and contains 'score' as one of its dimensions (others are 'timeStarted', 'authorUID', and 'TID')

So, this array is in disarray at this point and I need to organize it to where $searchResults[1] will be the highest 'score' and [2] will have the second highest, etc. I looked at array_multisort on php.net but got rapidly lost in how it worked. So how would I sort $searchResults in numeric order (rearrange the keys) descending with a descending order of a further dimension 'sort' as the sorting mechanism? There really isn't any code to go with it but if you need a layout of how the array looks, here you go:

$searchResults:
   [1] - ['timeStarted']
         ['authorUID']
         ['score']   <- Need to sort first dimension by this value descending
         ['TID']
   etc.

Thanks for any help.

1
  • the array is in disarray. hah i like it Commented Mar 26, 2011 at 3:31

2 Answers 2

5

usort allows sorting by any specified comparison function

$cmp = function($a,$b) {return $b['score'] - $a['score'];};
usort($searchResults, $cmp);

In this case, $cmp is a function that compares two elements $a and $b of $searchResults based on value of ['score']. $cmp returns 0 for equality, negative val if $a['score'] is greater, positive val if $b['score'] is greater. It would normally be the other way around, but a descending sorting order is desired.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I'll give it a whirl. I knew that usort could do things like this but the documentation on how it works internally were lacking and I was unsure of the mechanics by which is went through an array to sort - not knowing how it iterates internally caused problems when writing user-defined functions for it. Thanks!
you might have been overthinking - i personally dont know what the sorting algorithm is. in cases of equality, i dont know if order is preserved (stable vs unstable sort). but i dont need to know and thats the point of abstraction - i provide a comparison function of which i am confident and the sort works properly. hope it works out for you too.
0

The function you want is usort. Look at example #2:

<?php
function cmp($a, $b)
{
    return strcmp($a["fruit"], $b["fruit"]);
}

$fruits[0]["fruit"] = "lemons";
$fruits[1]["fruit"] = "apples";
$fruits[2]["fruit"] = "grapes";

usort($fruits, "cmp");

while (list($key, $value) = each($fruits)) {
    echo "\$fruits[$key]: " . $value["fruit"] . "\n";
}
?>

The output:

$fruits[0]: apples
$fruits[1]: grapes
$fruits[2]: lemons

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.