如何定义 usort 以使我的数组按特定顺序排序?
我正在尝试构建一个 php 类,它应该按照与输入的搜索查询的“相似性”顺序对来自 mysql 数据库的结果进行排序。我正在使用PHP函数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;
}
}
正如
您在函数“eachcmp”中看到的,我将数组中的每个值与 Base 进行比较,然后将所有值写入一个新数组。现在我的问题从这里开始。我现在如何按照 $ordered[]["sim"] 的顺序对数组进行排序?我知道我可能需要使用 usort,但我不知道该给哪个函数作为 usort 的参数。
谢谢帮助! phpheini
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,我认为您的函数应该如下所示:
否则您将在 $ordered 数组中创建新的数组元素。
现在介绍
usort
。usort
需要一个数组和一个比较函数。在 PHP >= 5.3 中,您可以使用 lambda 函数来实现这一点。适合您需要的比较函数可能如下所示:First of all, I think your function should look like this:
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: