英文:
Returning reference and manipulating specific variable in PHP multidimensional array
问题
我正在尝试从多维全局数组的特定位置返回引用,然后进行操作... 这是一个深度嵌套的数组。
我试过各种方法:
$foo = &get('bar');
$foo['something'] = 'for nothing';
var_dump($array); // 未受影响
function &get($search) {
global $array;
foreach(...) {
foreach(...) {
foreach(... as $key => &$val) {
if($val === $search) return $val;
}
}
}
}
这在PHP中可能不可行,但希望我错了,只是错过了一些明显的东西。
如果有更容易存储和操作复杂对象的方法,我并不一定要使用多维数组,只需要尽可能快。
谢谢任何建议!
英文:
I'm trying to return a reference from a specific position in a multidimensional global array and then manipulate it ... it's a deep nested array.
I'm trying to avoid having to iterate the array in every function that needs to manipulate a specific part.
I've tried all matter of this:
$foo = &get('bar');
$foo['something'] = 'for nothing';
var_dump($array); // unaffected
function &get($search) {
global $array;
foreach(...) {
foreach(...) {
foreach(... as $key => &val) {
if($val === $search) return &val;
}
}
}
}
This may not even be possible in PHP, but hoping I'm wrong and just missing something obvious.
Also, not married to a multidimensional array if there is an easier way to store and manipulate complex objects, it just needs to be as fast as possible.
Thanks for any advice!
答案1
得分: 1
I've fixed the syntax errors.
你的语法错误已经修复。
You need to use references for the iteration variables in all the foreach
loops.
在所有的 foreach
循环中,你需要使用引用来处理迭代变量。
You don't need to use &
when you're returning $val
, just return $val;
.
当你返回 $val
时,不需要使用 &
,只需写成 return $val;
。
To update, you should just assign directly to $foo
, since it doesn't contain an array.
要进行更新,你只需要直接赋值给 $foo
,因为它不包含数组。
英文:
I've fixed the syntax errors.
You need to use references for the iteration variables in all the foreach
loops.
You don't need to use &
when you're returning $val
, just return $val;
.
To update, you should just assign directly to $foo
, since it doesn't contain an array.
<?php
$array = [[["foo", "bar"]]];
$foo = &get('bar');
$foo = 'for nothing';
var_dump($array);
function &get($search) {
global $array;
foreach($array as &$level1) {
foreach($level1 as &$level2) {
foreach($level2 as &$val) {
if($val === $search) return $val;
}
}
}
}
Output:
array(1) {
[0]=>
array(1) {
[0]=>
array(2) {
[0]=>
string(3) "foo"
[1]=>
&string(11) "for nothing"
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论