说我有一个arrray:
$arr = array(
'Animal Dog',
'Subject Physics',
'Place Tokyo',
'Sport Tennis'
);
我希望usort
符合以下条件:如果它首先包含tokyo
排名,如果它包含tennis
排名第二,如果它包含dog
排名第三。
Place Tokyo,
Sport Tennis,
Animal Dog,
Subject Physics
我知道我可以使用stristr
来查看$a
和$b
中是否存在这些词语,但如果条件允许,我就无法写出这些词语......
function cmp($a,$b){
if ( stristr($a,'tokyo') )
// return what?
}
usort($arr, "cmp")
我将如何编写比较函数?
答案 0 :(得分:3)
这是一个多么奇怪的问题......这会做你正在寻找的事情吗?
usort($arr, 'cmp');
function cmp($a, $b) {
$av = (stripos($a, 'tokyo') !== false) * 4 | (stripos($a, 'tennis') !== false) * 2 | (stripos($a, 'dog') !== false);
$bv = (stripos($b, 'tokyo') !== false) * 4 | (stripos($b, 'tennis') !== false) * 2 | (stripos($b, 'dog') !== false);
return $av < $bv;
}
答案 1 :(得分:2)
试试这段代码。
$arr = array(
'Animal Dog3',
'Animal Dog1',
'Animal Dog2',
'Subject Physics',
'Place1 Tokyo',
'Place4 Tokyo',
'Sport Tennis'
);
$order_array = array('tokyo', 'tennis', 'dog');
$sort_function = function($a, $b) use($order_array)
{
$return = strcasecmp($a, $b);
foreach ($order_array as $word)
{
// if each string contains `tokyo` -- alphabetical order
if (stripos($a, $word) !== false && stripos($b, $word) !== false)
{
$return = strcasecmp($a, $b);
break;
}
// if $a string contains `tokyo` -- $a goes first
elseif (stripos($a, $word) !== false)
{
$return = -1;
break;
}
// if $b string contains `tokyo` -- $b goes first
elseif (stripos($b, $word) !== false)
{
$return = 1;
break;
}
// if $a and $b does not contains -- lets take `tennis`
else
{
continue; // just for readablity
}
}
return $return;
};
usort($arr, $sort_function);
var_dump($arr);
// ["Place1 Tokyo","Place4 Tokyo","Sport Tennis","Animal Dog1","Animal Dog2","Animal Dog3","Subject Physics"]
或者这个
$arr = array(
'Animal Dog3',
'Animal Dog1',
'Animal Dog2',
'Subject Physics',
'Place1 Tokyo',
'Place4 Tokyo',
'Sport Tennis'
);
$order_array = array('tokyo', 'tennis', 'dog');
$sort_function = function($a, $b) use($order_array)
{
$a_index = sizeof($order_array); // lets suppose that it's last
$b_index = sizeof($order_array); // lets suppose that it's last
$i = 0;
foreach ($order_array as $word)
{
if (stripos($a, $word) !== false)
$a_index = $i; // remeber index order of $a
if (stripos($b, $word) !== false)
$b_index = $i; // remeber index order of $b
$i++;
}
if ($a_index == $b_index) // if indexes are equal
return strcasecmp($a, $b); // alphabetical order
else
return $a_index - $b_index; // index order
};
usort($arr, $sort_function);
var_dump($arr);
// ["Place1 Tokyo","Place4 Tokyo","Sport Tennis","Animal Dog1","Animal Dog2","Animal Dog3","Subject Physics"]