Php foreach连续复制第一个var

Php foreach连续复制第一个var,php,arrays,foreach,Php,Arrays,Foreach,我试图根据表单中的数组生成查询条件,我就是这样做的: // will this suffice against sql injection? $filter_type = isset( $_POST['type'] ) ? filter_input( INPUT_POST , 'type', FILTER_SANITIZE_NUMBER_INT , FILTER_REQUIRE_ARRAY ) : NULL; $type_cond = ''; if ($filter_type != NULL)

我试图根据表单中的数组生成查询条件,我就是这样做的:

// will this suffice against sql injection?
$filter_type = isset( $_POST['type'] ) ? filter_input( INPUT_POST , 'type', FILTER_SANITIZE_NUMBER_INT , FILTER_REQUIRE_ARRAY ) : NULL;

$type_cond = '';
if ($filter_type != NULL) {
    foreach ($filter_type as $type=>$value) {
        if ($type === 0) {
            // need to add (int) before $value?
            $type_cond = "AND t2.type = " . $value;
        } else {
            $type_cond .= $type_cond . " OR t2.type = " . $value;
        }
    }
}
带有一个数组索引的输出:

AND t2.type = 1
具有两个数组索引的输出:

AND t2.type = 1AND t2.type = 1 OR t2.type = 2
AND t2.type = 1AND t2.type = 1 OR t2.type = 2AND t2.type = 1AND t2.type = 1 OR t2.type = 2 OR t2.type = 3
具有三个数组索引的输出:

AND t2.type = 1AND t2.type = 1 OR t2.type = 2
AND t2.type = 1AND t2.type = 1 OR t2.type = 2AND t2.type = 1AND t2.type = 1 OR t2.type = 2 OR t2.type = 3
为什么要连续重复这个过程?

因为:

$a .= $b;
导致将
$b
添加到
$a
的当前内容中。因此,如果您这样写:

$a .= $a . $b
$a
的内容添加到
$a
(因此重复),然后添加
$b
的内容

因此,您需要替换此:

$type_cond .= $type_cond . " OR t2.type = " . $value;
为此:

$type_cond .= " OR t2.type = " . $value;
一些链接:和^^