【发布时间】:2016-11-04 14:46:09
【问题描述】:
如何在 mysql codeigniter php 中使用 select 计算匹配的关键字?这是我的桌子
例如。假设搜索关键字为yes,测试
messages table
id | title | msg |date
---+-----------+-------------------+-------------+--
1 | test1 | yes | 2016-06-01 // 2 match keywords
2 | yes1 | no | 2016-06-02 // 1 match keywords
3 | test2 | no | 2016-06-03 // 1 match keywords
4 | yes2 | yes yes yes | 2016-06-04 // 4 match keywords
5 | yesyes3 | yes yes yes yes | 2016-06-05 // 6 match keywords
现在需要用 count_match 列显示
id | title | msg |date |count_match
---+-----------+-------------------+------------+-------------------
1 | test1 | yes | 2016-06-01 | 2
2 | yes1 | no | 2016-06-02 | 1
3 | test2 | no | 2016-06-03 | 1
4 | yes2 | yes yes yes | 2016-06-04 | 4
5 | yesyes3 | yes yes yes yes | 2016-06-05 | 6
对于数组,它应该显示如下
array (
[0] => array (
[id] => 5
[title] => yesyes3
[msg] => yes yes yes yes
[date] => 2016-06-05
[match] => 6
)
[1] => array (
[id] => 4
[title] => yes2
[msg] => yes yes yes
[date] => 2016-06-04
[match] => 4
)
[2] => array (
[id] => 1
[title] => test1
[msg] => yes
[date] => 2016-06-01
[match] => 2
)
[3] => array (
[id] => 3
[title] => test2
[msg] => no
[date] => 2016-06-03
[match] => 1
)
[4] => array (
[id] => 2
[title] => yes1
[msg] => no
[date] => 2016-06-02
[match] => 1
)
)
目前我的代码是这样的
$match = array('test','yes');
$orderbyString1 = "";
$orderbyString = "";
$likestr = "";
foreach($match AS $value)
{
$orderbyString .= "IF(m.title LIKE '%".$value."%' OR m.msg LIKE '%".$value."%',1,0)+";
$likestr .= "m.title LIKE '%".$value."%' OR m.msg LIKE '%".$value."%' OR ";
}
$orderbyString = substr($orderbyString, 0, -1);
$likestr = substr($likestr, 0, -4);
$this->db->select('m.*, ('.$orderbyString.') as count_match');
$this->db->from('messages m');
$this->db->where($likestr." ORDER BY ".$orderbyString." DESC");
$query = $this->db->get();
$results = $query->result_array();
print_r($results);exit;
有什么方法可以让 select 使用 php codeigniter 代码显示正确的 count_match 吗?因为目前它在 count_match 下显示 1 和 2。
谢谢!
【问题讨论】:
-
PHP 可以更容易地完成 - 循环数组并添加 substr_count() 的结果
-
您也可以使用regex,例如如果您需要无大小写匹配或单词边界。见demo at eval.in
-
@bobblebubble 谢谢,如果 msg = testyestest 并且 title = yestest 怎么样? match_count 应该是 5
-
感谢@splosh58 也得到了它,不过我只会在 php 中完成
-
@bobblebubble 只需在下面发布您的答案,以便我将其标记为该问题的解决方案。谢谢!
标签: php mysql arrays codeigniter select