2

我在 PHP 中构建深度嵌套的关联数组时遇到了麻烦。从我在这里和那里看到的问题/答案中,我收集到我应该使用参考资料,但我不知道该怎么做。

我正在使用 PHP 5.3

我正在解析一个看起来像 JSON 的文件。它包含用大括号括起来的嵌套“部分”,我想使用嵌套关联数组构建文件的树表示。

我从根部分和“当前部分”变量开始:

$rootSection = array();
$currentSection = $rootSection;
$sections = array();

当我进入一个新部分('{')时,我会这样做:

$currentSection[$newSectionName] = array();
array_push($sections, $currentSection);
$currentSection = $currentSection[$newSectionName];

我使用该$sections变量将部分('}')弹出到其父部分:

$currentSection = array_pop($sections);

最后,当我想向我的部分添加一个属性时,我基本上是这样做的:

$currentSection[$name] = $value;

我已经从上面的代码中删除了所有使用引用的尝试,因为到目前为止没有任何效果......我不妨说我习惯了 Javascript,其中引用是默认的......

但是PHP显然不是这种情况?我已经在我的解析代码中转储了我的变量,我可以看到所有属性都正确地添加到同一个数组中,但是rootSection数组或推入的数组$sections不会被相同地更新。

几个小时以来,我一直在寻找一种方法来做到这一点,但我真的不明白......所以请分享您可能对我有的任何帮助/指示!

更新:解决方案

感谢 chrislondon,我=&再次尝试使用,并设法使其工作。

初始化代码:

$rootSection = array();
$currentSection =& $rootSection;
$sections = array();

新部分('{'):

$currentSection[$newSectionName] = array();
$sections[] =& $currentSection;
$currentSection =& $currentSection[$newSectionName];

退出一个部分('}'):

$currentSection =& $sections[count($sections) - 1];
array_pop($sections);

请注意,从 PHP 5.3 开始,array_push($a, &$b);不推荐使用类似的操作并触发警告。$b =& array_pop($a)也是不允许的;这就是为什么我使用[]=/运算符在我的数组[]中推送/“pop” 。$sections

我最初遇到的问题实际上是推送/弹出到我的部分堆栈,我无法维护对数组的引用并且不断获取副本。

谢谢你的帮助 :)

4

1 回答 1

1

如果你想通过引用传递一些东西,=&像这样使用:

$rootSection = array();
$currentSection =& $rootSection;

$currentSection['foo'] = 'bar';

print_r($rootSection);
// Outputs: Array ( [foo] => bar )

我也见过这样的语法,$currentSection = &$rootSection;但它们在功能上是相同的。

于 2013-06-11T03:21:43.240 回答