这是我的表格,我需要使用codeigniter创建一个搜索功能,该功能将显示包含按大多数匹配关键字和最新添加日期排序的关键字的项目列表。
实施例。提交的两个关键字是yes,test
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
现在预期输出将显示:
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('yes','test');
$array = array('m.title' => $match, 'm.msg' => $match);
$this->db->select('m.*');
$this->db->from('messages m');
$this->db->like($array);
$this->db->order_by('m.date', 'DESC');
$query = $this->db->get();
是否有任何php codeigniter代码?
谢谢!
答案 0 :(得分:1)
您需要使用搜索字词创建ORDER BY子句。
所以完整代码
<强> EDITED 强>
$match = array('yes','test');
//$array = array('m.title' => $match, 'm.msg' => $match);//you do not need this
$orderbyString = "";
$likestr = "";
//first prepare an ORDER BY statement and like statement
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");
//$this->db->order_by($orderbyString, 'DESC');//removed this line
$query = $this->db->get();
$results = $query->result_array();//contains the desired result