tags:

views:

163

answers:

3

I'm writing a script in PHP that compares people together based on the number of same answers in a survey. I use an array like this:

[person ID]=>number of answers same

to store the 10 people closest to the one I am comparing with.

I need to figure out how to find the lowest of the 10 number of answers same and overwrite a higher number of answers same and modify the person ID key with it.

Any help?

+2  A: 

Sounds like you could solve this in SQL very easily, but will require a great deal of work to do in PHP.

Allain Lalonde
+1  A: 

Wouldn't it just be easier to keep your array sorted by number of same answers? Maybe even just add the new person, resort the array and remove the first/last..

Tim
It's always the obvious!
+1  A: 

You need to sort the entries according to the delta to person.number_of_answers. Eg.:

function cmp_by_delta($a, $b) {
  if ($a->delta == $b->delta) {
    return 0;
  }
  return ($a->delta < $b->delta) ? -1 : 1;
}
// calculate delta for each entry
foreach ($entries as $person) {
  $person->delta = abs($target_person->number_of_answers - $person->number_of_answers);
}
// sort entries by delta
usort($entries, 'cmp_by_delta');
// take 10 first matches from sorted array
$10_best_matches = array_slice($entries, 0, 10);

Of course, this can be done much prettier and much more efficiently in a database:

select * from people
order by abs(number_of_answers - :target_number_of_answers)
limit 10;
troelskn