如何定义我的数组的usort按特定顺序排序?

I am trying to build a php class which should sort my results coming from a mysql database in the order of their "similarity" to the entered search query. I am using the php function similar_text.

class compare { 

static $_base = NULL; 

static function setBase($base) { 
    if (!isset ($base) or !is_string($base)) { 
        $base = "";
    } 
    self::$_base = strtolower($base); 
} 

static function cmp($a) { 
    if (!is_string(self::$_base)){ 
        self::setBase(); 
    } 
    similar_text(self::$_base, strtolower($a), $a_pct); 
    return $a_pct;  
}

static function eachcmp($src, $arr)
{
    $ordered = array();
    foreach($arr as $key => $val)
    {
        $sim = cmp($val);
        $ordered[]["something"] = $arr[$key]["something"];
        $ordered[]["something2"] = $arr[$key]["something2"];
        $ordered[]["sim"] = $sim;
    }
}   

}

As you can see in the function "eachcmp" I am comparing each value in the array with the Base and then writing all the values into a new array. Now my problem starts here. How can I now order the array in the order of $ordered[]["sim"]? I know I probably need to use usort, but I dont know which function to give as parameters for usort.

Thx for help! phpheini

First of all, I think your function should look like this:

static function eachcmp($src, $arr)
{
    $ordered = array();
    foreach($arr as $key => $val)
    {
        $sim = cmp($val);
        $data = array();
        $data["something"] = $arr[$key]["something"];
        $data["something2"] = $arr[$key]["something2"];
        $data["sim"] = $sim;
        $ordered[] = $data;
    }
}   

Otherwise you would be creating the new array elements in the $ordered array.

Now for the usort. usort expects an array and a comparison function. In PHP >= 5.3 you can use lambda functions for that. A suitable comparison function for your need might look like this:

 usort($ordered, function($a, $b) {
    $al = intval($a["sim"]);
    $bl = intval($a["sim"]);
    if ($al == $bl) {
        return 0;
    }
    return ($al > $bl) ? +1 : -1;
 });