PHP、数组和引用

标签 php arrays reference

为什么下面的代码不能像我预期的那样工作?

<?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
                )                   
        )
)

最佳答案

如果您按如下两行修改代码:

$area = array();

$section = array();

为此:

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

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

它将按预期工作。

在第一个版本中,$area$section 充当指向 $root 数组中值的“指针”。如果您先重置值,这些变量随后可用于创建全新的数组,而不是覆盖以前的数组。

关于PHP、数组和引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42876/

相关文章:

javascript - 如何将javascript返回的php变量值传递给php变量?

python - 如何在 numpy 中内部连接两个数组?

php - 如何在 PHP 数组中查找重复项?

arrays - 将数组指针传递给另一个类并为将来保留一个引用 - Swift

java - 关于简洁类模型/模式的建议,以解决方法中的多个细微变化

php - 将过滤器从接受今天更改为同时接受昨天+今天

php - 考试成绩由高到低排序

reference - `&` 和 `ref` 有什么区别?

C++ 指向 const 的指针

c++ - 将右值分配给 'const auto&' 时会发生什么