如何从 foreach 循环的末尾删除字符串


how to remove string from the end of foreach loop

我可以从循环的末尾删除ORforeach

if (isset($_POST['size'])) {
                    $where .= ' AND ';
                    $s = $_POST['size'];
                    $end = count($s);
                    foreach ($s as $ss) {
                        $where .= 'pSize=' . $ss;
                        $where .= ' OR ';
                    }
                } else {
                    $s = '';
                }

根据您的条件,我认为您使用IN很容易。

if (isset($_POST['size'])) {
    $size = $_POST['size'];
    if($size){
         $where .= ' AND `pSize` IN ('.implode(",", $size).')';
    }
}

也适用于您的情况:

if (isset($_POST['size'])) {
                    $where .= ' AND ';
                    $s = $_POST['size'];
                    $end = count($s);
                    for($i=0;$i<count($s);$i++) {
                        $where .= 'pSize=' . $s[$i];
                        if($i != count($s)-1){
                        $where .= ' OR ';
                       }
                    }
                } else {
                    $s = '';
                }

避免该问题的一种方法是创建一个数组并内爆。

if (isset($_POST['size'])) {
    $where .= ' AND (';
    $s = $_POST['size'];
    $end = count($s);
    //echo $end;
    $aWhere = [];
    foreach ($s as $ss) {
        $aWhere[] =  'pSize=' . $ss;
    }
    $where .= implode(' OR ', $aWhere) . ')';
} else {
    $s = '';
}

也许你需要在"哪里"上加括号,我为你做了。

注意SQL注入,使用预准备语句。

你可以选择多种方式 方式1: 你可以选择for循环而不是foreach()

$a=sizeof($s);
$x=$a-1;
for($i=0;$i<$a;$i++){
if($i==$x){ $where .= 'pSize=' . $ss;
                       }
else{                   $where .= 'pSize=' . $ss;
                        $where .= ' OR ';
}
} 

方式2:使用rtrim()

 foreach ($s as $ss) {
                        $where .= 'pSize=' . $ss;
                        $where .= ' OR ';
                    }
$where=rtrim($where,' OR ');

有很多方法可以做到这一点。您甚至可以使用 for 循环。如果您更喜欢 foreach 循环,可以创建一个迭代器变量来模拟 for 循环,如下所示:

if (isset($_POST['size'])) {
                    $where .= ' AND ';
                    $s = $_POST['size'];
                    $end = count($s);
                    $i = 0;
                    foreach ($s as $ss) {
                        $where .= 'pSize=' . $ss;
                        if (++$i != $end) 
                            $where .= ' OR ';
                    }
} else {
     $s = '';
}