2014-04-06 6 views
4

중첩 루프에서 배열을 다시 루프하고 배열을 변경해도 되나요? 이 항목의 경우 example.com동일한 배열에서 중첩 된 foreach 루프 사용

:

나는 URL 또는 도메인 중 하나의 (배열의 키와 같은) 항목이있는 URL의 배열을했습니다 도메인 : example.com 내가 예를 포함하는 모든 URL을 제거하려면 .COM 도메인으로 : 그 위에 두 번째 루프 아무 문제가 없습니다

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]); 
       } 
      } 
     } 
    } 
+0

확실히 반복해도 괜찮습니다. 그러나 나는 그걸 수정하는 것이 좋다고 확신하지 못합니다. –

+0

['array_walk'] (http://php.net/array_walk) 또는 ['array_map'] (http://php.net/array_map)을하는 것이 더 나을 수도 있습니다. 이 코드가 제대로 작동하면 변경해야 할 이유가 없습니다. –

+1

http://stackoverflow.com/questions/10057671/how-foreach-actually-works?rq=1 http://stackoverflow.com/questions/1685689/how-is-an-array-in- a-php-foreach-loop-read? rq = 1 http://stackoverflow.com/questions/2008866/unsetting-array-values-in-a-foreach-loop?rq=1 –

답변

2

당신이 항목을 제거하기 시작하면, 그러나 당신은 큰 매듭으로 자신과 코드를 얻을 것이다. 내 제안 사본을 저장하고 수정하는 것입니다.

이상적인 것은 아니지만 원하는 것을 잘 모르겠습니다.

//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]); 
      } 
     } 
    } 
} 
0

비슷한 문제가있어서 배열 복사본을 만드는 것이 답이었습니다. 이것은 내 문제였습니다 :

파일의 시작 부분에 특정 텍스트 문자열이 있고 (약 80 명의 구성원으로 이루어진 배열) 파일의 끝 부분에 문자열이 일치하는 경우 끝에 3 개의 줄을 제거해야했습니다. 내가 사본을 사용하지 않았을 때 일어난 문제는 색인이 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++ 
       } 
      } 
     } 

    } 

}