Mongolid\Cursor\EmbeddedCursor::sort PHP Method

sort() public method

Sorts the results by given fields.
public sort ( array $fields ) : EmbeddedCursor
$fields array An array of fields by which to sort. Each element in the array has as key the field name, and as value either 1 for ascending sort, or -1 for descending sort.
return EmbeddedCursor Returns this cursor.
    public function sort(array $fields)
    {
        foreach (array_reverse($fields) as $key => $value) {
            // Uses usort with a function that will access the $key and sort in
            // the $value direction. It mimics how the mongodb does sorting
            // internally.
            usort($this->items, function ($a, $b) use($key, $value) {
                $a = is_object($a) ? $a->{$key} ?? null : $a[$key] ?? null;
                $b = is_object($b) ? $b->{$key} ?? null : $b[$key] ?? null;
                if ($a < $b) {
                    return $value * -1;
                }
                return $value;
            });
        }
        return $this;
    }