You are here

protected function SearchApiMultiQuery::compareResults in Search API Multi-Index Searches 7

Compare two result arrays.

Callback for uasort() within searchMultiple().

Parameters

array $a: One result.

array $b: The other result.

Return value

int A negative number if $a should come before $b, 0 if both compare equal and a positive number otherwise.

File

./search_api_multi.query.inc, line 986

Class

SearchApiMultiQuery
Standard implementation of SearchApiMultiQueryInterface.

Code

protected function compareResults(array &$a, array &$b) {
  foreach ($this->sort as $key => $order) {

    // Get the sorting for this specific field.
    if ($key == 'search_api_relevance') {
      $comp = $a['score'] - $b['score'];
    }
    elseif ($key == 'search_api_id') {
      if (is_numeric($a['id']) && is_numeric($b['id'])) {
        $comp = $a['id'] - $b['id'];
      }
      else {
        $comp = strnatcasecmp($a['id'], $b['id']);
      }
    }
    else {
      list($index_id, $field) = explode(':', $key, 2);
      $a_applies = $a['index_id'] == $index_id;
      $b_applies = $b['index_id'] == $index_id;
      if ($a_applies == $b_applies) {
        if (!$a_applies) {
          continue;
        }
        $value_a = $a['fields'][$field];
        $value_b = $b['fields'][$field];
        if (is_numeric($value_a) && is_numeric($value_b)) {
          $comp = $value_a - $value_b;
        }
        else {
          $comp = strnatcasecmp($value_a, $value_b);
        }
      }
      else {
        $comp = $a_applies ? -1 : 1;

        // When the sort only applies to one of the two results, we always
        // want it in front of the other, regardless of $order.
        $order = 'ASC';
      }
    }

    // Now apply the specified order and either return or continue.
    if (!$comp) {
      continue;
    }
    return (int) ($order == 'ASC' ? $comp : -$comp);
  }
  return 0;
}