Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add additional parameters to usort/uasort cmp function?

Tags:

php

I would like to have this $sort_flags array available within the compare_by_flags function, but I didn't find a way to this, is it possible?

public function sort_by_rank(array $sort_flags = array()) {
    uasort($this->search_result_array, array($this, 'compare_by_flags'));
}

private static function compare_by_flags($a, $b) {
    // I want to have this $sort_flags array here to compare according to those flags      
}
like image 539
Riesling Avatar asked Sep 12 '11 12:09

Riesling


2 Answers

If you use php < 5.3 then you can just use instance variables:

public function sort_by_rank(array $sort_flags = array()) {
    $this->sort_flags = $sort_flags;
    uasort($this->search_result_array, array($this, 'compare_by_flags'));
}

private static function compare_by_flags($a, $b) {
    // I want to have this $sort_flags array here to compare according to those flags      
}

otherwise - use closures:

public function sort_by_rank(array $sort_flags = array()) {
    uasort($this->search_result_array, function($a, $b) use ($sort_flags) {
        // your comparison
    });
}
like image 155
zerkms Avatar answered Oct 14 '22 17:10

zerkms


You don't mention what you want to achieve by passing the $sort_flags variable, but you might find this answer of mine useful (either as it stands, or as an example if you want to achieve something different).

like image 34
Jon Avatar answered Oct 14 '22 16:10

Jon