4
爲什麼下面的代碼不能像我期待的那樣工作?PHP,數組和參考
<?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);
預期結果:
Array(
[Area1] => Array(
[Section1] => Array(
[0] => Location1
)
)
[Area2] => Array(
[Section2] => Array(
[0] => Location2
)
)
)
實際結果:
Array(
[Area1] => Array(
[Section2] => Array(
[0] => Location2
)
)
[Area2] => Array(
[Section2] => Array(
[0] => Location2
)
)
)