2011-02-23 6 views
35

foreach 루프가 있는데 루프의 다음 요소가 있는지 확인하여 현재 요소를 다음 요소와 비교할 수 있는지 확인합니다. 어떻게해야합니까? 현재와 ​​다음 기능에 대해 읽었지만 사용법을 알 수는 없습니다. 사전에foreach 루프의 다음 요소 가져 오기

덕분에

+0

요소 # 2에서 시작하여 요소 # 1과 비교해도됩니까? –

+0

아니요 1에서 시작해야합니다 – chchrist

답변

24

독특한 접근 방식은 배열과 다음 루프를 반대하는 것입니다. 이뿐만 아니라 비 숫자 인덱스 배열을 위해 작동합니다

$items = array(
    'one' => 'two', 
    'two' => 'two', 
    'three' => 'three' 
); 
$backwards = array_reverse($items); 
$last_item = NULL; 

foreach ($backwards as $current_item) { 
    if ($last_item === $current_item) { 
     // they match 
    } 
    $last_item = $current_item; 
} 

여전히 currentnext 기능을 사용하여에 관심이 있다면, 당신이 할 수 있습니다 :

$items = array('two', 'two', 'three'); 
$length = count($items); 
for($i = 0; $i < $length - 1; ++$i) { 
    if (current($items) === next($items)) { 
     // they match 
    } 
} 

# 2는 아마도 최고입니다 해결책. 참고로 $i < $length - 1;은 배열의 마지막 두 항목을 비교 한 후 루프를 중지합니다. 나는 이것을 예제에 명시하기 위해 루프에 넣었다. 이 간단한 배열 모두 작동합니다

//$arr is the array you wish to cycle through 
$keys = array_keys($arr); 
$num_keys = count($keys); 
$i = 1; 
foreach ($arr as $a) 
{ 
    if ($i < $num_keys && $arr[$keys[$i]] == $a) 
    { 
     // we have a match 
    } 
    $i++; 
} 

: 당신은 아마 그냥 $length = count($items) - 1;

6

인덱스는 continious 아칸소 경우

foreach($arr as $key => $val){ 
    if(isset($arr[$key+1])){ 
     echo $arr[$key+1]; // next element 
    }else{ 
    //end of array reached 
    } 
} 
+1

이것은 사실이 아니므로 try : array (1 => 'a', 0 => 'b', 100 => 'c'); –

+7

@EduardoRomero 옙, 그 이유는 언급했다 :'인덱스가 계속되면 ' –

4

를 그 숫자 색인 경우 :

foreach ($foo as $key=>$var){ 

    if($var==$foo[$key+1]){ 
     echo 'current and next var are the same'; 
    } 
} 
1

당신은 다음의 foreach는 전에 배열의 키를 얻을 다음의 요소를 확인하기 위해 카운터를 사용할 수있는 뭔가를 계산한다 array(1,2,3)과 같은 키 배열과 array('first'=>1, 'second'=>2, 'thrid'=>3)과 같은 키 배열이 있습니다. php.net/foreach로서

8

지적 : 어레이가 참조

않는

의 Foreach가 지정된 배열의 복사본이 아닌 배열 자체에서 동작한다. foreach는 배열 포인터에 몇 가지 부작용이 있습니다. foreach 중에 또는 후에 배열 포인터를 다시 설정하지 않고 배열 포인터에 의존하지 마십시오.

다른 말로하면, 당신이하고 싶은 것을하는 것은 그리 좋은 생각이 아닙니다. 아마도 당신이 왜이 일을하려는 이유에 대해 누군가와 이야기를 나누고 더 나은 해결책이 있는지 알아 보는 것이 좋습니다. 사용 가능한 다른 리소스가 없다면 ## PHP on irc.freenode.net로 언제든지 물어보십시오.

9

당신은 아마 사용할 수있는 동안 대신 foreach는 루프 :

while ($current = current($array)) 
{ 
    $next = next($array); 
    if (false !== $next && $next == $current) 
    { 
     //do something with $current 
    } 
} 
+0

이 도움이되었다 ... 감사합니다! –

+0

포인터가 첫 번째 요소로 설정되지 않았으므로,이 작업을하기 전에'reset ($ array) '해야 할 수도 있습니다. – Jonathan

0

next()prev() 기능이 쓸모 만들기, 원래 배열의 복사본을 반복합니다 PHP에서 foreach 루프. 당신이 연관 배열을 가지고 있고 다음 항목을 가져 오기 위해 필요한 경우, 대신 배열 키를 반복 수 :

foreach (array_keys($items) as $index => $key) { 
    // first, get current item 
    $item = $items[$key]; 
    // now get next item in array 
    $next = $items[array_keys($items)[$index + 1]]; 
} 

을 키의 결과 배열이 연속 인덱스 자체를 가지고 있기 때문에, 당신은에 액세스하는 대신에 사용할 수 있습니다 원래 배열.지난 이후에는 다음 항목이 없기 때문에

는, 마지막 반복에 대한 null 될 것 $next주의하십시오. 존재하지 않는 배열 키에 액세스하면 PHP 알림이 ​​표시됩니다. index + 1와 키는 다음과 같이 수있는 방법이에게 전체 foreach 문을 사용하여 array_key_exists()

로 존재하는 경우

  1. 값을 할당하기 전에 마지막 반복에 대한 확인 $next
  2. 확인하려면 다음 중 하나,이를 방지하려면 :

    foreach (array_keys($items) as $index => $key) { 
        // first, get current item 
        $item = $items[$key]; 
        // now get next item in array 
        $next = null; 
        if (array_key_exists($index + 1, array_keys($items))) { 
         $next = $items[array_keys($items)[$index + 1]]; 
        } 
    } 
    
+1

각 반복마다 array_keys를 사용 하시겠습니까? 가장 느린 솔루션이어야합니다. – Semra

2

일반적인 해결 방법은 캐싱 반복자가 될 수 있습니다. 올바르게 구현 된 캐싱 반복자는 모든 반복자와 작동하며 메모리를 저장합니다. PHP SPL은 CachingIterator이지만 매우 이상하며 기능이 매우 제한적입니다. 그러나 다음과 같이 직접 미리보기 반복자를 작성할 수 있습니다.

<?php 

class NeighborIterator implements Iterator 
{ 

    protected $oInnerIterator; 

    protected $hasPrevious = false; 
    protected $previous = null; 
    protected $previousKey = null; 

    protected $hasCurrent = false; 
    protected $current = null; 
    protected $currentKey = null; 

    protected $hasNext = false; 
    protected $next = null; 
    protected $nextKey = null; 

    public function __construct(Iterator $oInnerIterator) 
    { 
     $this->oInnerIterator = $oInnerIterator; 
    } 

    public function current() 
    { 
     return $this->current; 
    } 

    public function key() 
    { 
     return $this->currentKey; 
    } 

    public function next() 
    { 
     if ($this->hasCurrent) { 
      $this->hasPrevious = true; 
      $this->previous = $this->current; 
      $this->previousKey = $this->currentKey; 
      $this->hasCurrent = $this->hasNext; 
      $this->current = $this->next; 
      $this->currentKey = $this->nextKey; 
      if ($this->hasNext) { 
       $this->oInnerIterator->next(); 
       $this->hasNext = $this->oInnerIterator->valid(); 
       if ($this->hasNext) { 
        $this->next = $this->oInnerIterator->current(); 
        $this->nextKey = $this->oInnerIterator->key(); 
       } else { 
        $this->next = null; 
        $this->nextKey = null; 
       } 
      } 
     } 
    } 

    public function rewind() 
    { 
     $this->hasPrevious = false; 
     $this->previous = null; 
     $this->previousKey = null; 
     $this->oInnerIterator->rewind(); 
     $this->hasCurrent = $this->oInnerIterator->valid(); 
     if ($this->hasCurrent) { 
      $this->current = $this->oInnerIterator->current(); 
      $this->currentKey = $this->oInnerIterator->key(); 
      $this->oInnerIterator->next(); 
      $this->hasNext = $this->oInnerIterator->valid(); 
      if ($this->hasNext) { 
       $this->next = $this->oInnerIterator->current(); 
       $this->nextKey = $this->oInnerIterator->key(); 
      } else { 
       $this->next = null; 
       $this->nextKey = null; 
      } 
     } else { 
      $this->current = null; 
      $this->currentKey = null; 
      $this->hasNext = false; 
      $this->next = null; 
      $this->nextKey = null; 
     } 
    } 

    public function valid() 
    { 
     return $this->hasCurrent; 
    } 

    public function hasNext() 
    { 
     return $this->hasNext; 
    } 

    public function getNext() 
    { 
     return $this->next; 
    } 

    public function getNextKey() 
    { 
     return $this->nextKey; 
    } 

    public function hasPrevious() 
    { 
     return $this->hasPrevious; 
    } 

    public function getPrevious() 
    { 
     return $this->previous; 
    } 

    public function getPreviousKey() 
    { 
     return $this->previousKey; 
    } 

} 


header("Content-type: text/plain; charset=utf-8"); 
$arr = [ 
    "a" => "alma", 
    "b" => "banan", 
    "c" => "cseresznye", 
    "d" => "dio", 
    "e" => "eper", 
]; 
$oNeighborIterator = new NeighborIterator(new ArrayIterator($arr)); 
foreach ($oNeighborIterator as $key => $value) { 

    // you can get previous and next values: 

    if (!$oNeighborIterator->hasPrevious()) { 
     echo "{FIRST}\n"; 
    } 
    echo $oNeighborIterator->getPreviousKey() . " => " . $oNeighborIterator->getPrevious() . " ----->  "; 
    echo "[ " . $key . " => " . $value . " ]  -----> "; 
    echo $oNeighborIterator->getNextKey() . " => " . $oNeighborIterator->getNext() . "\n"; 
    if (!$oNeighborIterator->hasNext()) { 
     echo "{LAST}\n"; 
    } 
} 
관련 문제