Php 在同一数组上使用嵌套的foreach循环

Php 在同一数组上使用嵌套的foreach循环,php,Php,是否可以在嵌套循环中再次循环数组并更改数组 我有一个URL数组,其中包含URL或域的条目(作为数组键):example.com 对于以下条目:domain:example.com,我想删除包含example.com作为域的所有URL: foreach (array_keys($urls1) as $line) { if (preg_match('/domain:(.*)/i', $line, $matches)) { $domain = $matches[

是否可以在嵌套循环中再次循环数组并更改数组

我有一个URL数组,其中包含URL或域的条目(作为数组键):example.com

对于以下条目:domain:example.com,我想删除包含example.com作为域的所有URL:

foreach (array_keys($urls1) as $line) {
        if (preg_match('/domain:(.*)/i', $line, $matches)) {
            $domain = $matches[1];
            foreach (array_keys($urls1) as $line2) {
                if ($url_domains[$line2] == $domain) {
                    unset($urls1[$line2]);
                }
            }
        }
    }

第二次循环是没有问题的,但是如果您开始删除项目,您和您的代码将陷入一个大结。我的建议是保存一份副本并修改它

这并不理想,但我不确定你想做什么

//Make a copy of your array
$URLCopy  = $urls1;

foreach (array_keys($urls1) as $line) {
    if (preg_match('/domain:(.*)/i', $line, $matches)) {
        $domain = $matches[1];
        foreach (array_keys($urls1) as $line2) {
            if ($url_domains[$line2] == $domain) {
                unset($URLCopy[$line2]);
            }
        }
    }
 }

我遇到了一个类似的问题,答案就是复制数组。这就是我的问题:

如果在文件开头存在一个特定的文本字符串,并且(大约80个成员的数组)在文件末尾匹配一个字符串,那么我必须在文件末尾删除三行。我没有使用副本时出现的问题是索引会从30重置为9,这给我带来了一些问题

这就是我的工作

$rowCopy = $row

foreach($row as $index => &$line) {

    ////previous code

    if ($line[0] === "NM1" && $line[1] === "77") {
        //read through the $row array and find the NM*85 string
        foreach ($rowCopy as $index2 => $lineT) {

            if ($s = strpos($lineT, "NM1*85") !== false) {
                $npiTest = explode("*", $lineT);
                if (strcmp(preg_replace("/[^0-9,.]/", "", $npiTest[9]), $line[9]) === 0) {
                    // $line = false;
                    $index--;
                    unset($row[$index + 1]);
                    $index++;
                    unset($row[$index + 1]);
                    $index++;
                    unset($row[$index + 1]);
                    $erased = $erased + 3;
                    $index++
                }
            }
        }

    }

}

绕着它转一圈当然没关系。但我不确定是否可以修改它以及如何修改它。最好是使用or。如果它与这段代码配合得很好,我看不出有任何理由更改它。