[英]Sort search results from MySQL by the position of the search query in the string using PHP
我希望我的搜索結果按照從最小到最大的字符串位置的順序排列。 例如,搜索“banana”返回:
嬰兒食品,李子,香蕉和米飯,緊張
香蕉,脫水或香蕉粉
香蕉,原料
面包,香蕉,從配方准備,用人造黃油制成
CAMPBELL Soup Company,V8 SPLASH果汁飲料,草莓香蕉
CAMPBELL Soup Company,V8 SPLASH冰沙,草莓香蕉
CAMPBELL Soup Company,V8 V. FUSION Juices,Strawberry Banana
因為“香蕉”是結果的第一個字所以想要“香蕉,原始”,並且因為“香蕉”是最后一個字所以想要“CAMPBELL Soup ...”最后登場。
我知道我可以使用strpos()來找到位置,但是如何將它們放在一起呢?
您可以在MySQL中輕松完成此操作。
SELECT title,LOCATE('banana',title)
FROM myTable
WHERE LOCATE('banana',title) > 0
ORDER BY LOCATE('banana',title)
title表示MySql表的列。
您也可以選擇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;
它將涉及一個不必要的復雜的usort
或類似的PHP,最好在查詢中執行,例如:
SELECT data, INSTR(data, 'banana') as index
FROM table
WHERE data LIKE '%banana%'
ORDER BY index != 0, index
如果你只是想模仿strpos:
select col, locate('banana', col) as pos from t
order by pos < 1, pos, length(col)
如果您沒有從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端進行一些額外的計算......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.