1

我正在尝试根据标签搜索照片表。

我将搜索词拆分为单独的关键字,并在表格中搜索每个单独的关键字,将任何匹配项推送到数组中。

$keywords = explode(' ', $keywords);
$photos = array();

// loop through each keyword
foreach($keywords as $keyword){

$row = $mysqli->query(" SELECT * FROM photos WHERE tags LIKE '%$keyword%' ");

// loop through each row result
    while( $query_result = $row->fetch_assoc() ){

        // push result to photos array
        array_push($photos, $query_result);

    }

}

但是,这可能会多次返回同一个表格行,例如,如果我搜索“mod modded”,任何带有“modded”标签的照片都将被推到数组顶部两次,因为它匹配两个关键字。

如何确保只选择一行?

编辑

感谢您的回复,但都没有奏效,我已经实现了我所追求的:

$keywords = explode(' ', $keywords);
$photos = array();

// loop through each keyword
foreach($keywords as $keyword){

    $row = $mysqli->query(" SELECT * FROM photos WHERE tags LIKE '%$keyword%' ");

    // loop through each row result
    while( $query_result = $row->fetch_assoc() ){

        $dontPush = false;

        // check photos array to see if the query_result already exists
        foreach($photos as $photo){
            if($photo == $query_result){
                $dontPush = true;
            }
        }

        if($dontPush === false){
            // push result to photos array if it dodesnt already exist
            array_push($photos, $query_result);
        }

    }

}

但这会产生如此多的循环,如果我有一个大数据库,返回结果肯定需要很长时间?有没有更好的办法

4

3 回答 3

1

尝试这个

<?php 
$keywords = explode(' ', $keywords);
$photos = array();

$query = " SELECT * FROM photos ";

// loop through each keyword
foreach($keywords as $k => $keyword){

    if ($k==0) {
       $query .= " WHERE ";
    }

    $query .= " tags LIKE '%$keyword%' ";

    if ($k-1 < count($keywords)) {
       $query .= " OR ";
    }
}

$row = $mysqli->query( $query );
while( $query_result = $row->fetch_assoc() ){

    // push result to photos array
    array_push($photos, $query_result);

}
?>
于 2013-10-19T13:02:49.403 回答
1

尝试选择不同

SELECT DISTINCT * FROM photos WHERE tags LIKE '%$keyword%'

W3 学校

或者,您也可以在末尾添加 LIMIT 1 以仅返回第一行。

于 2013-10-19T12:55:19.697 回答
0

对于任何有兴趣的人,我设法解决了这个问题,以确保不返回重复项:

$keywords = explode(' ', $keywords);
$photos = array();
$query = " SELECT * FROM photos WHERE tags LIKE ";

// loop through each keyword
foreach($keywords as $i => $keyword){

    $query .= "'%$keyword%'";

    if($i+1 < count($keywords) ){
        $query .= " union SELECT * FROM photos WHERE tags LIKE ";
    }


}

$row = $mysqli->query( $query );

// loop through each row result
while( $query_result = $row->fetch_assoc() ){

    array_push($photos, $query_result);

}
于 2013-10-19T14:07:45.443 回答