使用 PHP 根据搜索查询在字符串中的位置对来自 MySQL 的搜索结果进行排序
我希望我的搜索结果按字符串位置从小到大的顺序排列。 例如,搜索“香蕉”会返回:
婴儿食品、李子、香蕉和大米、滤过的
香蕉、脱水或香蕉粉
香蕉、生
面包、香蕉、按照食谱制备、用人造黄油制作
CAMPBELL Soup Company、V8 SPLASH 果汁饮料、草莓Banana
CAMPBELL Soup Company, V8 SPLASH Smoothies, Strawberry Banana
CAMPBELL Soup Company, V8 V. FUSION Juices, Strawberry Banana
我希望“Bananas, raw”排在第一位,因为“banana”是结果中的第一个单词,并且我希望“CAMPBELL”汤......”最后出现,因为“香蕉”是最后一个词。
我知道我可以使用 strpos() 来查找位置,但如何将它们放在一起?
I want my search results to be in order of string position from smallest to greatest.
For example, searching for "banana" returns:
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
I want "Bananas, raw" to come first because "banana" is the first word in the result, and I want "CAMPBELL Soup..." to come up last because "banana" is the last word.
I know I can use strpos() to find the position, but how do I put it all together?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以在 MySQL 中轻松完成此操作。
title 代表 MySql 表的列。
You can do this easily in MySQL.
title represent column of MySql table.
它将涉及不必要的复杂
usort
或 PHP 中的类似内容,最好在查询中执行此操作,例如:It will involve a needlessly complex
usort
or something similar in PHP, best to do it in the query, for example:您还可以选择 INSTR(titles, 'banana') 作为firstIndex 并按该值 ASC 排序。这将返回大海捞针中第一个找到的针的索引。标记
WHERE
子句,省略任何不是LIKE
'%banana%'
的内容,您应该进行设置:You could also select
INSTR(titles, 'banana') as firstIndex
and order by that value, ASC. This will return the index of the first located index of the needle within the haystack. Tag on aWHERE
clause that omits anything that isn'tLIKE
'%banana%'
and you should be set:如果您没有从 SQL 查询中获取该数据,您可以使用
usort
和stripos
;像这样的事情应该做:即你在这里用你自己定义的函数进行排序,该函数比较“Banana”在它作为参数接收的两个字符串中的位置(不区分大小写)。
排序后,您将获得数组的这种输出:
当然,如果您从 SQL 查询中获取该数据,那么在 SQL 端进行一些额外的计算可能会更容易......
If you don't get that data from an SQL query, you can sort that using
usort
andstripos
; something like this should do :i.e. you are here sorting with you own defined function, that compares the position (case-insentive) of "Banana" in the two strings it receives as parameters.
And you'll get this kind of output for your array, once sorted :
Of course, if you get that data from an SQL query, it might be easier to do some additionnal calculations on the SQL side...
如果你只是想模拟 strpos:
if you just want to emulate strpos: