草庐IT

php - 通过引用浏览数组正在更改它(未完成任何操作)

coder 2024-04-17 原文

edit:不要看相关的topic,下面的答案很清楚并给出了解决方案,而另一个topic只是陈述了问题。

我这里有一些奇怪的东西

我的代码是这样的:

        var_dump($resultFlatTree);
        foreach($resultFlatTree as &$element)
        {
            /*if(isset($element["action"]) && $element["action"] == "new")
            {
                //let's save the original ID so we can find the children
                $originalID = $element["id"];
                //now we get the object
                $newObject = $setUpForDimension->createAnObject($dimension,$element,$customer);
                $element['id'] = $newObject->getId();
                echo "new";
                //and let's not forget to change the parent_id of its children
                $arrayFunctions->arrayChangingValues($resultFlatTree,"parent_id",$element['id'],$originalID);
                $em->persist($newObject);                                                             
            } */               
        }            
        $em->flush();
        var_dump($resultFlatTree);

对 foreach 中的代码进行了注释,以确保改变数组的不是我正在做的事情。

这里是 foreach 之前的数组:

array(3) {
  [0]=>
  array(10) {
    ["id"]=>
    int(2)
    ["name"]=>
    string(7) "Revenue"
    ["code"]=>
    string(6) "700000"
    ["sense"]=>
    string(2) "CR"
    ["lft"]=>
    int(1)
    ["lvl"]=>
    int(2)
    ["rgt"]=>
    int(1)
    ["root"]=>
    int(1)
    ["$$hashKey"]=>
    string(3) "00D"
    ["parent_id"]=>
    int(1)
  }
  [1]=>
  array(10) {
    ["id"]=>
    int(3)
    ["name"]=>
    string(7) "Charges"
    ["code"]=>
    string(6) "600000"
    ["sense"]=>
    string(2) "DR"
    ["lft"]=>
    int(3)
    ["lvl"]=>
    int(2)
    ["rgt"]=>
    int(4)
    ["root"]=>
    int(1)
    ["$$hashKey"]=>
    string(3) "00P"
    ["parent_id"]=>
    int(4)
  }
  [2]=>
  array(10) {
    ["id"]=>
    int(4)
    ["name"]=>
    string(6) "Energy"
    ["code"]=>
    string(6) "606000"
    ["sense"]=>
    string(2) "DR"
    ["lft"]=>
    int(2)
    ["lvl"]=>
    int(1)
    ["rgt"]=>
    int(5)
    ["root"]=>
    int(1)
    ["$$hashKey"]=>
    string(3) "00E"
    ["parent_id"]=>
    int(1)
  }
}

然后是:

array(3) {
  [0]=>
  array(10) {
    ["id"]=>
    int(2)
    ["name"]=>
    string(7) "Revenue"
    ["code"]=>
    string(6) "700000"
    ["sense"]=>
    string(2) "CR"
    ["lft"]=>
    int(1)
    ["lvl"]=>
    int(2)
    ["rgt"]=>
    int(1)
    ["root"]=>
    int(1)
    ["$$hashKey"]=>
    string(3) "00D"
    ["parent_id"]=>
    int(1)
  }
  [1]=>
  array(10) {
    ["id"]=>
    int(3)
    ["name"]=>
    string(7) "Charges"
    ["code"]=>
    string(6) "600000"
    ["sense"]=>
    string(2) "DR"
    ["lft"]=>
    int(3)
    ["lvl"]=>
    int(2)
    ["rgt"]=>
    int(4)
    ["root"]=>
    int(1)
    ["$$hashKey"]=>
    string(3) "00P"
    ["parent_id"]=>
    int(4)
  }
  [2]=>
  &array(10) {
    ["id"]=>
    int(4)
    ["name"]=>
    string(6) "Energy"
    ["code"]=>
    string(6) "606000"
    ["sense"]=>
    string(2) "DR"
    ["lft"]=>
    int(2)
    ["lvl"]=>
    int(1)
    ["rgt"]=>
    int(5)
    ["root"]=>
    int(1)
    ["$$hashKey"]=>
    string(3) "00E"
    ["parent_id"]=>
    int(1)
  }
}

如您所见,最后一个元素现在已更改并通过引用。 这完全打乱了我之后对阵列所做的处理。

这是正常行为吗? 我怎样才能避免它?

最佳答案

当您通过引用传递给 foreach 语句时,您真的应该阅读文档 :)

http://php.net/manual/en/control-structures.foreach.php

In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.

<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
    $value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
unset($value); // break the reference with the last element
?>

即使在 foreach 循环之后,$value 和最后一个数组元素的引用仍然存在。建议通过unset()销毁。

基本上,它是说当你经过 ref 时,由于内部指针,它会保持锁定在最后一个项目上。

第二次用户评论在 40 分时:

“即使在 foreach 循环之后,$value 的引用和最后一个数组元素仍然存在。建议通过 unset() 销毁它。”

我怎么强调文档的这一点都不为过!这是一个简单的例子,说明为什么必须这样做:

<?php
$arr1 = array("a" => 1, "b" => 2, "c" => 3);
$arr2 = array("x" => 4, "y" => 5, "z" => 6);

foreach ($arr1 as $key => &$val) {}
foreach ($arr2 as $key => $val) {}

var_dump($arr1);
var_dump($arr2);
?>

输出是:

array(3) { ["a"]=> int(1) ["b"]=> int(2) ["c"]=> &int(6) }
array(3) { ["x"]=> int(4) ["y"]=> int(5) ["z"]=> int(6) }

注意 $arr1 中的最后一个索引现在是 $arr2 中最后一个索引的值!

如果您在该链接中查找“引用”,您会发现更多有趣的评论。

长话短说: 这有点有趣/错误/奇怪/未打补丁。 在编写代码时了解其含义并为它们留出空间。

关于php - 通过引用浏览数组正在更改它(未完成任何操作),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27481171/

有关php - 通过引用浏览数组正在更改它(未完成任何操作)的更多相关文章

  1. ruby-on-rails - Ruby on Rails 迁移,将表更改为 MyISAM - 2

    如何正确创建Rails迁移,以便将表更改为MySQL中的MyISAM?目前是InnoDB。运行原始执行语句会更改表,但它不会更新db/schema.rb,因此当在测试环境中重新创建表时,它会返回到InnoDB并且我的全文搜索失败。我如何着手更改/添加迁移,以便将现有表修改为MyISAM并更新schema.rb,以便我的数据库和相应的测试数据库得到相应更新? 最佳答案 我没有找到执行此操作的好方法。您可以像有人建议的那样更改您的schema.rb,然后运行:rakedb:schema:load,但是,这将覆盖您的数据。我的做法是(假设

  2. ruby-on-rails - 在 Ruby 中循环遍历多个数组 - 2

    我有多个ActiveRecord子类Item的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:ItemAmaintenancerequiredin5daysItemBpaymentrequiredin6daysItemApaymentrequiredin7daysItemBmaintenancerequiredin8days我目前有两个查询,用于查找maintenance和payment项目(非排他性查询),并输出如下内容:paymentrequiredin...maintenancerequiredin...有什么方法可以改善上述(丑陋的)代

  3. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

    我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

  4. ruby - 多次弹出/移动 ruby​​ 数组 - 2

    我的代码目前看起来像这样numbers=[1,2,3,4,5]defpop_threepop=[]3.times{pop有没有办法在一行中完成pop_three方法中的内容?我基本上想做类似numbers.slice(0,3)的事情,但要删除切片中的数组项。嗯...嗯,我想我刚刚意识到我可以试试slice! 最佳答案 是numbers.pop(3)或者numbers.shift(3)如果你想要另一边。 关于ruby-多次弹出/移动ruby​​数组,我们在StackOverflow上找到一

  5. ruby - 通过 rvm 升级 ruby​​gems 的问题 - 2

    尝试通过RVM将RubyGems升级到版本1.8.10并出现此错误:$rvmrubygemslatestRemovingoldRubygemsfiles...Installingrubygems-1.8.10forruby-1.9.2-p180...ERROR:Errorrunning'GEM_PATH="/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/ruby-1.9.2-p180@global:/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/rub

  6. ruby - 将数组的内容转换为 int - 2

    我需要读入一个包含数字列表的文件。此代码读取文件并将其放入二维数组中。现在我需要获取数组中所有数字的平均值,但我需要将数组的内容更改为int。有什么想法可以将to_i方法放在哪里吗?ClassTerraindefinitializefile_name@input=IO.readlines(file_name)#readinfile@size=@input[0].to_i@land=[@size]x=1whilex 最佳答案 只需将数组映射为整数:@land边注如果你想得到一条线的平均值,你可以这样做:values=@input[x]

  7. ruby - 通过 erb 模板输出 ruby​​ 数组 - 2

    我正在使用puppet为ruby​​程序提供一组常量。我需要提供一组主机名,我的程序将对其进行迭代。在我之前使用的bash脚本中,我只是将它作为一个puppet变量hosts=>"host1,host2"我将其提供给bash脚本作为HOSTS=显然这对ruby​​不太适用——我需要它的格式hosts=["host1","host2"]自从phosts和putsmy_array.inspect提供输出["host1","host2"]我希望使用其中之一。不幸的是,我终其一生都无法弄清楚如何让它发挥作用。我尝试了以下各项:我发现某处他们指出我需要在函数调用前放置“function_”……这

  8. ruby - 检查数组是否在增加 - 2

    这个问题在这里已经有了答案:Checktoseeifanarrayisalreadysorted?(8个答案)关闭9年前。我只是想知道是否有办法检查数组是否在增加?这是我的解决方案,但我正在寻找更漂亮的方法:n=-1@arr.flatten.each{|e|returnfalseife

  9. ruby - 通过 ruby​​ 进程共享变量 - 2

    我正在编写一个gem,我必须在其中fork两个启动两个webrick服务器的进程。我想通过基类的类方法启动这个服务器,因为应该只有这两个服务器在运行,而不是多个。在运行时,我想调用这两个服务器上的一些方法来更改变量。我的问题是,我无法通过基类的类方法访问fork的实例变量。此外,我不能在我的基类中使用线程,因为在幕后我正在使用另一个不是线程安全的库。所以我必须将每个服务器派生到它自己的进程。我用类变量试过了,比如@@server。但是当我试图通过基类访问这个变量时,它是nil。我读到在Ruby中不可能在分支之间共享类变量,对吗?那么,还有其他解决办法吗?我考虑过使用单例,但我不确定这是

  10. ruby - 通过 RVM (OSX Mountain Lion) 安装 Ruby 2.0.0-p247 时遇到问题 - 2

    我的最终目标是安装当前版本的RubyonRails。我在OSXMountainLion上运行。到目前为止,这是我的过程:已安装的RVM$\curl-Lhttps://get.rvm.io|bash-sstable检查已知(我假设已批准)安装$rvmlistknown我看到当前的稳定版本可用[ruby-]2.0.0[-p247]输入命令安装$rvminstall2.0.0-p247注意:我也试过这些安装命令$rvminstallruby-2.0.0-p247$rvminstallruby=2.0.0-p247我很快就无处可去了。结果:$rvminstall2.0.0-p247Search

随机推荐