up vote 0 down vote favorite

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?

link|flag

Can you rephrase "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."? I can't understand what you are asking. You should have already noticed: English is not my idiom of choice. – Eineki Jan 27 '09 at 16:45
Hmm. I need to keep an array full of the 10 highest matches. This problem was solved according to Tim's reccomendation – user29772 Jan 28 '09 at 23:33

3 Answers

up vote 1 down vote accepted

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..

link|flag
It's always the obvious! – user29772 Jan 27 '09 at 19:24
up vote 2 down vote

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

link|flag
up vote 1 down vote

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;
link|flag

Your Answer

 
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.