如何使用codeigniter php为搜索函数查找最匹配的关键字

如何使用codeigniter php为搜索函数查找最匹配的关键字,php,mysql,arrays,codeigniter,search,Php,Mysql,Arrays,Codeigniter,Search,这是我的表格,我需要使用codeigniter创建一个搜索函数,该函数将显示包含我的关键字的项目列表,按匹配关键字的最多数量和添加的最新日期排序 两个提交的关键字是yes,test messages table id | title | msg |date ---+-----------+-------------------+-------- 1 | test1 | yes | 2016-06-01 //

这是我的表格,我需要使用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代码用于此


谢谢

您需要使用搜索词创建ORDERBY子句

那么完整的代码呢

已编辑

$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

嗨@aj,谢谢,但是那场比赛会回来吗?它将如何在数组中显示?我得到一个错误:严重性:注意消息:数组到字符串的转换正确,因此它将是
$match='yes test但是foreach呢?它必须在arrayalmost中,但我得到了这些错误“要在附近使用的语法”如“%”ESCAPE“!”orderbyif(`我认为使用
$orderbyString
可能重复的