How to pass usort() a parameter?

2020-01-19 07:12发布

问题:

My code:

function sortx($a, $b) {
    if(!strpos($a["p_title"],'apple ipad')) {
        return -1; 
    }
    return 1;
}
usort($arr, 'sortx');`

In above function I want to pass: $sort_text='apple ipad'; , when calling function instead of hardcoding apple ipad into strpos(). How can I accomplish that?

回答1:

Call it with a closure:

$sort_text='apple ipad';
usort(
    $arr, 
    function ($a, $b) use ($sort_text) {
        if(!strpos($a["p_title"], $sort_text)) {
            return -1; 
        }
        return 1;
    }
);

and you can pass additional arguments with the use clause