我希望我的搜索结果按照从最小到最大的字符串位置的顺序排列。 例如,搜索“banana”会返回:
香蕉,脱水或香蕉粉
香蕉,原料
面包,香蕉,由配方制成,用人造黄油制成
坎贝尔汤公司,V8 SPLASH果汁饮料,草莓香蕉
CAMPBELL Soup Company,V8 SPLASH冰沙,草莓香蕉
CAMPBELL Soup Company,V8 V. FUSION Juices,Strawberry Banana
我希望“Bananas,raw”首先来,因为“香蕉”是结果中的第一个单词,我想要“CAMPBELL Soup ...”最后出现,因为“香蕉”是最后一个词。
我知道我可以使用strpos()来找到位置,但是如何将它们放在一起呢?
答案 0 :(得分:3)
您可以在MySQL中轻松完成此任务。
SELECT title,LOCATE('banana',title)
FROM myTable
WHERE LOCATE('banana',title) > 0
ORDER BY LOCATE('banana',title)
title表示MySql表的列。
答案 1 :(得分:0)
您也可以选择INSTR(titles, 'banana') as firstIndex
并按该值ASC排序。这将返回大海捞针内第一个定位索引的索引。标记WHERE
子句,忽略任何非LIKE
'%banana%'
的内容,您应该设置:
SELECT id, pubdate, title, INSTR(title, 'tea') as `index`
FROM article
WHERE title LIKE '%tea%'
ORDER BY `index` ASC;
答案 2 :(得分:0)
它将涉及一个不必要的复杂usort
或类似的PHP,最好在查询中执行,例如:
SELECT data, INSTR(data, 'banana') as index
FROM table
WHERE data LIKE '%banana%'
ORDER BY index != 0, index
答案 3 :(得分:0)
如果你只是想模仿strpos:
select col, locate('banana', col) as pos from t
order by pos < 1, pos, length(col)
答案 4 :(得分:0)
如果您没有从SQL查询中获取该数据,则可以使用usort
和stripos
对其进行排序;这样的事情应该做:
$arr = array(
"Babyfood, plums, bananas and rice, strained",
"Bananas, dehydrated, or banana powder",
"Bananas, raw",
"Bread, banana, prepared from recipe, made with margarine",
"CAMPBELL Soup Company, V8 SPLASH Juice Drinks, Strawberry Banana",
"CAMPBELL Soup Company, V8 SPLASH Smoothies, Strawberry Banana",
"CAMPBELL Soup Company, V8 V. FUSION Juices, Strawberry Banana",
);
function compare_position($a, $b) {
return stripos($a, 'banana') - stripos($b, 'banana');
}
usort($arr, 'compare_position');
var_dump($arr);
即。你在这里用自己定义的函数进行排序,比较它收到的两个字符串中“Banana”的位置(case-insentive)作为参数。
一旦排序,你就会得到这种数组输出:
$ /usr/local/php-5.3/bin/php temp.php
array(7) {
[0]=>
string(37) "Bananas, dehydrated, or banana powder"
[1]=>
string(12) "Bananas, raw"
[2]=>
string(56) "Bread, banana, prepared from recipe, made with margarine"
[3]=>
string(43) "Babyfood, plums, bananas and rice, strained"
[4]=>
string(61) "CAMPBELL Soup Company, V8 SPLASH Smoothies, Strawberry Banana"
[5]=>
string(61) "CAMPBELL Soup Company, V8 V. FUSION Juices, Strawberry Banana"
[6]=>
string(64) "CAMPBELL Soup Company, V8 SPLASH Juice Drinks, Strawberry Banana"
}
当然,如果从SQL查询中获取数据,那么在SQL端进行一些额外的计算可能会更容易......