你能帮我处理这个foreach循环吗?

dldeef67  于 2021-06-21  发布在  Mysql
关注(0)|答案(3)|浏览(283)
$cat_id=$_GET['cat_id'];
$catEx = explode(' ',$cat_id);
foreach($catEx as $exCat)
{
    $looped .= 'ad_cat LIKE'.' '.'%'."$exCat".'%'.' OR '.'ad_title LIKE'.' '.'%'."$exCat".'%'.' OR '.'ad_sub_cat LIKE'.' '.'%'."$exCat".'%'.' OR '.'ad_description LIKE'.' '.'%'."$exCat".'%' ;
}

我需要让搜索栏搜索多个单词。

mzillmmw

mzillmmw1#

你可以试试这个代码

$cat_id=$_GET['cat_id'];//cute cat
$catEx = explode(' ',$cat_id);
$looped = [];
foreach($catEx as $exCat) {
    $looped[] = "ad_cat         LIKE '%$exCat%' OR 
                 ad_title       LIKE '%$exCat%' OR 
                 ad_sub_cat     LIKE '%$exCat%' OR 
                 ad_description LIKE '%$exCat%'";
}
echo implode(" OR ",$looped);
vkc1a9a2

vkc1a9a22#

在每组like条件周围添加括号,以便在每列中检查每个值。

$cat_id=$_GET['cat_id'];
$catEx = explode(' ',$cat_id);
foreach($catEx as $exCat) {
    $looped .= "(ad_cat         LIKE '%$exCat%' OR 
                 ad_title       LIKE '%$exCat%' OR 
                 ad_sub_cat     LIKE '%$exCat%' OR 
                 ad_description LIKE '%$exCat%') OR ";
}
$looped = trim($looped,' OR '); //just added some spaces
hzbexzde

hzbexzde3#

正如@aynber在评论中所说的,使用sprintf

sprintf ( 'column like "%%s%" or column like "%%s%"', 'string', 'string');

相关问题