2008-09-04 8 views
4

Warum funktioniert der folgende Code nicht wie erwartet?PHP, Arrays und Referenzen

<?php 
$data = array(
    array('Area1', null, null), 
    array(null, 'Section1', null), 
    array(null, null, 'Location1'), 
    array('Area2', null, null), 
    array(null, 'Section2', null), 
    array(null, null, 'Location2') 
); 
$root = array(); 
foreach ($data as $row) { 
    if ($row[0]) { 
     $area = array(); 
     $root[$row[0]] =& $area; 
    } elseif ($row[1]) { 
     $section = array(); 
     $area[$row[1]] =& $section; 
    } elseif ($row[2]) { 
     $section[] = $row[2]; 
    } 
} 
print_r($root); 

Erwartetes Ergebnis:

Array(
    [Area1] => Array(       
      [Section1] => Array(
        [0] => Location1 
       )     
     ) 
    [Area2] => Array(   
      [Section2] => Array(    
        [0] => Location2 
       )     
     ) 
) 

Tatsächliches Ergebnis:

Array(
    [Area1] => Array(       
      [Section2] => Array(
        [0] => Location2 
       )     
     ) 
    [Area2] => Array(   
      [Section2] => Array(    
        [0] => Location2 
       )     
     ) 
) 

Antwort

3

Wenn Sie Ihren Code auf zwei Zeilen wie folgt ändern:

$area = array(); 

$section = array(); 

dazu:

unset($area); 
$area = array(); 

unset($section); 
$section = array(); 

wird es wie erwartet funktionieren.

In der ersten Version, $area und $section werden als „Zeiger“ auf den Wert innerhalb des $root Array fungieren. Wenn Sie die Werte zuerst zurücksetzen, können diese Variablen verwendet werden, um neue Arrays zu erstellen, anstatt die vorherigen Arrays zu überschreiben.

1

Dies wird auch funktioniert:

$root[$row[0]] = array(); 
$area =& $root[$row[0]];