2016-10-25 2 views
0

foreach 루프 내에 다른 값 배열을 추가하고 있습니다.foreach 루프의 배열 값을 다시 채우십시오.

$i = true; 
$array = array('red', 'blue'); 
foreach($array as $key => & $value) { 
    echo $value . '<br />'; 
    if ($i === true) { 
     $others = array('white', 'yellow'); 
     foreach($others as $key => & $other_value) { 
      $array[] = $other_value;  
     } 
    } 
    $i = false; 
} 

내가 foreach 루프 내부에 배열 값을 개편 할

red 
blue 
white 
yellow 

하지만 출력

red 
white 
yellow 
blue 
+1

재편성이란 무엇입니까? –

+0

처음부터 끝까지 배열을 반복합니다. 이 반복 중에 어떤 종류의'reshufling '을하는 것은 나에게 쓸모없는 것처럼 보이고 루프의 예상치 못한 동작을 초래할 수 있습니다. –

+0

BTW, 새로운 배열을 배열에 추가하는 것은 한 줄의 코드에서'array_merge'로 할 수 있습니다. –

답변

1

당신은 몇 가지 심각한없이 $array에 그것을 할 수 없습니다 아래와 같은 출력을 필요로 array_slice() ing. 그래서, 또 다른 배열 $result에 할당하면 $array의 제 1 및 제 2 요소 사이에 삽입 된 $other 배열을 얻을 것이다 : 멋진 솔루션처럼 $array = $result;

1

것 (어떤 이유) 필요한 경우

$i = true; 
$array = array('red', 'blue'); 
foreach($array as $value) { 
    $result[] = $value; // here... 
    if ($i === true) { 
     $others = array('white', 'yellow'); 
     foreach($others as $other_value) { 
      $result[] = $other_value; // and here... 
     } 

    } 
    $i = false; 
} 

을 이 :

$array = array('red', 'blue'); 
$others = array('white', 'yellow'); 

$temp = array_combine($array,$others); 

$final = array(); 

foreach($temp as $key => $value) { 
    array_push($final,$key,$value); 
} 

$array = $final; 
0
$i = true; 
$array = array('red', 'blue'); 
foreach($array as $key => & $value) { 
    echo $value . '<br />'; 
    if ($i === true) { 
      $a1= $array; 
      $a2= array($value); 
      $result=array_diff($a1,$a2); 

      $others = array('white', 'yellow'); 
      $array = array_merge($others,$result); 
    } 
    $i = false; 
} 

see output