2011-10-12 4 views
0

가능한 중복 :
Why does PHP overwrite values when I iterate through this array twice (by reference, by value)PHP 배열의 foreach에 의해 엉망이됩니다

내가 print_r의 경우처럼 보이는 배열을 가지고 : 이제 때

Array 
(
    [0] => Array 
     (
      [0] => 13 
      [product_id] => 13 
      [1] => 1 
      [account_id] => 1 
      [vat type] => 0 
      [vat included] => 0 
      [price] => 3 
      [unit] => test3 
      [product number] => 3 
     ) 
    [1] => Array 
     (
      [0] => 12 
      [product_id] => 12 
      [1] => 1 
      [account_id] => 1 
      [vat type] => 1 
      [vat included] => 0 
      [price] => 2 
      [unit] => test2 
      [product number] => 2 
     ) 
    [2] => Array 
     (
      [0] => 11 
      [product_id] => 11 
      [1] => 1 
      [account_id] => 1 
      [vat type] => 2 
      [vat included] => 0 
      [price] => 1 
      [unit] => test1 
      [product number] => 1 
     ) 
) 

을 foreach를 사용하여 루프를 돌리면 이상한 일이 발생합니다. foreach 루프의 각 하위 배열 print_r을 보면 다음과 같습니다.

Array 
(
    [0] => 13 
    [product_id] => 13 
    [1] => 1 
    [account_id] => 1 
    [vat type] => 0 
    [vat included] => 0 
    [price] => 3 
    [unit] => test3 
    [product number] => 3 
) 
Array 
(
    [0] => 12 
    [product_id] => 12 
    [1] => 1 
    [account_id] => 1 
    [vat type] => 1 
    [vat included] => 0 
    [price] => 2 
    [unit] => test2 
    [product number] => 2 
) 
Array 
(
    [0] => 12 
    [product_id] => 12 
    [1] => 1 
    [account_id] => 1 
    [vat type] => 1 
    [vat included] => 0 
    [price] => 2 
    [unit] => test2 
    [product number] => 2 
) 

세 번째 항목에 주목하십시오. 나에게는 신비 롭다. 왜 이런 일이 일어나는 지 아는 사람이 있습니까?

+0

: 에 있음을 교체? –

+0

당신의 foreach 코드를 보여줄 수 있습니까? –

+1

내 돈은 참조 된 변수 ('foreach ($ array as & $ foo)')를 재사용한다고 말합니다 ... – deceze

답변

2

'deceze'의 의견은 문제를 거의 해결했습니다.

foreach($products as &$product){ 

를하고 이상이 $ 제품에 일부 항목을 추가 : 내가 사용.

foreach($products as $key=>$product){ 

와 $를 수정 제품 [$ 키]

감사합니다 = D를 문제를 해결 번째 목록을하시기 바랍니다 생성하는 데 사용하여 foreach는 코드를 추가 할 수

+1

또는 루프 뒤에서 간단히'unset ($ product)'할 수 있습니다. – deceze