在PHP多维数组中返回引用并操作特定变量。

huangapple go评论87阅读模式
英文:

Returning reference and manipulating specific variable in PHP multidimensional array

问题

我正在尝试从多维全局数组的特定位置返回引用,然后进行操作... 这是一个深度嵌套的数组。

我试过各种方法:

  1. $foo = &get('bar');
  2. $foo['something'] = 'for nothing';
  3. var_dump($array); // 未受影响
  4. function &get($search) {
  5. global $array;
  6. foreach(...) {
  7. foreach(...) {
  8. foreach(... as $key => &$val) {
  9. if($val === $search) return $val;
  10. }
  11. }
  12. }
  13. }

这在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:

  1. $foo = &get('bar');
  2. $foo['something'] = 'for nothing';
  3. var_dump($array); // unaffected
  4. function &get($search) {
  5. global $array;
  6. foreach(...) {
  7. foreach(...) {
  8. foreach(... as $key => &val) {
  9. if($val === $search) return &val;
  10. }
  11. }
  12. }
  13. }

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.

  1. <?php
  2. $array = [[["foo", "bar"]]];
  3. $foo = &get('bar');
  4. $foo = 'for nothing';
  5. var_dump($array);
  6. function &get($search) {
  7. global $array;
  8. foreach($array as &$level1) {
  9. foreach($level1 as &$level2) {
  10. foreach($level2 as &$val) {
  11. if($val === $search) return $val;
  12. }
  13. }
  14. }
  15. }

Output:

  1. array(1) {
  2. [0]=>
  3. array(1) {
  4. [0]=>
  5. array(2) {
  6. [0]=>
  7. string(3) "foo"
  8. [1]=>
  9. &string(11) "for nothing"
  10. }
  11. }
  12. }

huangapple
  • 本文由 发表于 2023年8月5日 05:07:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76839112.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定