具有preg_match的循环数组

时间:2019-04-17 15:12:47

标签: php

我试图遍历一个多维数组,寻找匹配项(preg_match())。我遇到的错误都是未初始化的字符串偏移量和空正则表达式。我认为我没有正确循环数组。

该数组包含数据库中的数据,我在其中存储类型的ID,要匹配的字符串以及如果匹配则需要分配的类型名称。

array(3) { 
    [0]=> array(3) { 
        [0]=> string(1) "1" 
        [1]=> string(7) "/call/i" 
        [2]=> string(14) "Telephone call" } 
    [1]=> array(3) { 
        [0]=> string(1) "2" 
        [1]=> string(10) "/contact/i" 
        [2]=> string(7) "Contact" } 
    [2]=> array(3) { 
        [0]=> string(1) "3" 
        [1]=> string(10) "/meeting/i" 
        [2]=> string(7) "Meeting" } 
        }
$filterQuery = "SELECT ID, matchstring, type FROM rulesdes";
            $results = mysqli_query($this->connection, $filterQuery);
            while ($row = mysqli_fetch_array($results, MYSQLI_NUM)) {
                $array[] = $row;
            }

foreach ($array as $value){
                foreach ($value as $types){
                    if (preg_match($types[1], $subject)){
                        $emailType = $array[1];
                    } else {
                        $emailType = "All emails";
                    }
                    $queryType = "INSERT INTO rules (ID, Type) VALUES ('$id', '$emailType')";
                    mysqli_query($this->connection, $queryType);
                }
            }

一旦匹配,它将保存类型的名称,并将其发送给具有唯一ID的数据库。

尝试过AbraCadaver的解决方案(无效):

            $filterQuery = "SELECT ID, matchstring, type FROM rulesdes";
            $results = mysqli_query($this->connection, $filterQuery);
            while ($row = mysqli_fetch_array($results, MYSQLI_NUM)) {
                $array[] = $row;
            }
            foreach ($array as $values){
                if (strpos($subject, $values[1])){
                    $emailType = $values[2];
                } else {
                    $emailType = "All emails";
                }
                $queryType = "INSERT INTO rules (ID, Type) VALUES ('$id', '$emailType')";
                mysqli_query($this->connection, $queryType);
            }

1 个答案:

答案 0 :(得分:1)

您只需要一个循环,然后访问每个数组中的数组元素:

foreach ($array as $values){
    $id = $values[0];

    if (preg_match($values[1], $subject)){
        $emailType = $values[2];
    } else {
        $emailType = "All emails";
    }
    $queryType = "INSERT INTO rules (ID, Type) VALUES ('$id', '$emailType')";
    mysqli_query($this->connection, $queryType);
}

但是,存储callcontactmeeting并使用strpos会更容易,更快捷:

    if (strpos($subject, $values[1]) !== false){
        $emailType = $values[2];
    } else {
        $emailType = "All emails";
    }