我试图在 PHP 的嵌套 foreach 循环中使用指针修改值。 然而,以下行似乎不起作用:
// Assign a the attribs value to the array
$link_row['value'] = $args[ $u_value ];
变量$args[ $u_value ];已填充并且可以毫无问题地输出,但是当我将它添加到 $link_row 引用时它似乎没有设置..
foreach ($unique_links as $link_id => &$link_attr)
{
foreach($link_attr as &$link_row)
{
foreach($link_row as $u_attr => &$u_value)
{
if ($u_attr == 'attribute_name')
{
// Assign a the attribs value to the array
$link_row['value'] = $args[ $u_value ];
// If one of the values for the unique key is blank,
// we can remove the entire
// set from being checked
if ( !isset($args[ $u_value ]) )
{
unset($unique_links[$link_id] );
}
}
}
}
}
最佳答案
在 foreach 中使用变量后,您必须始终取消设置变量。即使你有两个 foreach(..) 语句一个接一个。即使您在另一个 foreach(..) 中有一个 foreach(..)。 没有异常(exception)!
foreach ($unique_links as $link_id => &$link_attr)
{
foreach($link_attr as &$link_row)
{
foreach($link_row as $u_attr => &$u_value)
{
if ($u_attr == 'attribute_name')
{
// Assign a the attribs value to the array
$link_row['value'] = $args[ $u_value ];
// If one of the values for the unique key is blank,
// we can remove the entire
// set from being checked
if ( !isset($args[ $u_value ]) )
{
unset($unique_links[$link_id] );
}
}
}
unset($u_value); // <- this is important
}
unset($link_row); // <- so is this
}
unset($lnk_attr); // <- and so is this, even if you reached the end of your program or the end of a function or a method and even if your foreach is so deeply indented or on such a long line that you're not sure what code might follow it, because another developer (maybe even you) will come back and read the code and he might not see that you used a reference in a foreach
这是不久前搞砸了一个大项目的另一段有趣的代码:
foreach ($data as $id => &$line) {
echo "This is line {$id}: '{$line}'\n";
$line .= "\n";
}
echo "And here is the output, one line of data per line of screen:\n";
foreach ($data as $id => &$line) {
echo $line;
}
事实上,有人没有在第一个 foreach(..) 之后立即 unset($line) 确实弄乱了数组中的数据,因为 &$line 是一个引用,第二个 foreach(..) 为它分配了一个不同的值,因为它循环遍历数据并不断覆盖最后一行数据。
关于PHP foreach 和引用资料,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4267701/
我想让一个yaml对象引用另一个,如下所示:intro:"Hello,dearuser."registration:$introThanksforregistering!new_message:$introYouhaveanewmessage!上面的语法只是它如何工作的一个例子(这也是它在thiscpanmodule中的工作方式。)我正在使用标准的rubyyaml解析器。这可能吗? 最佳答案 一些yaml对象确实引用了其他对象:irb>require'yaml'#=>trueirb>str="hello"#=>"hello"ir
我正在尝试将一个资源属性的默认值设置为另一个属性的值。我正在为我正在构建的tomcat说明书定义一个资源,其中包含以下定义。我想要可以独立设置的“名称”和“服务名称”属性。当未设置服务名称时,我希望它默认为为“名称”提供的任何内容。以下不符合我的预期:attribute:name,:kind_of=>String,:required=>true,:name_attribute=>trueattribute:service_name,:kind_of=>String,:default=>:name注意第二行末尾的“:default=>:name”。当我在Recipe的新block中引用我
如thisanswer中所述,Array.new(size,object)创建一个数组,其中size引用相同的object。hash=Hash.newa=Array.new(2,hash)a[0]['cat']='feline'a#=>[{"cat"=>"feline"},{"cat"=>"feline"}]a[1]['cat']='Felix'a#=>[{"cat"=>"Felix"},{"cat"=>"Felix"}]为什么Ruby会这样做,而不是对object进行dup或clone? 最佳答案 因为那是thedocumenta
假设我有一个可枚举对象enum,现在我想获取第三个项目。我知道一种通用方法是转换成数组,然后使用索引访问,如:enum.to_a[2]但这种方式会创建一个临时数组,效率可能很低。现在我使用:enum.each_with_index{|v,i|breakvifi==2}但这非常丑陋和多余。执行此操作最有效的方法是什么? 最佳答案 你可以使用take剥离前三个元素,然后剥离last从take给你的数组中获取第三个元素:third=enum.take(3).last如果您根本不想生成任何数组,那么也许:#Ifenumisn'tanEnum
代码:threads=[]Thread.abort_on_exception=truebegin#throwexceptionsinthreadssowecanseethemthreadseputs"EXCEPTION:#{e.inspect}"puts"MESSAGE:#{e.message}"end崩溃:.rvm/gems/ruby-2.1.3@req/gems/activesupport-4.1.5/lib/active_support/dependencies.rb:478:inload_missing_constant':自动加载常量MyClass时检测到循环依赖稍加研究后,
我正在跟踪我们的应用程序(ruby2.1)中的内存泄漏问题。我正在使用这两种技术:ObjectSpace.dump_all将所有对象转储到JSON流,然后进行离线分析。我使用的第二种技术是使用ObjectSpace.reachable_objects_from进行实时分析。在这两种方式中,我发现我泄漏的对象被一个对象RubyVM::Env引用。任何人都可以向我解释什么是RubyVM::Env。如何删除这些引用? 最佳答案 RubyVM::Env是一个包含变量引用的内部ruby类。这是我的测试:require'objspace'a
这个问题不是很有用因为themethodreferenceoperatorwasremovedfromRuby2.7.0发布前。由于历史原因,这个问题被搁置了。Ruby2.7.0-preview1引入了方法引用运算符.:作为实验性功能。(更多here和here)。有一些抽象示例可用于说明如何使用这个新运算符:method=42.:to_s=>#method.receiver=>42method.name=>:to_smethod.call=>"42"和:method=File.:read=>#method.call('/Users/foo/.zshrc')=>"exportZSH=$H
在我的应用程序中我有classUserincludeUser::FooendUser::Foo定义在app/models/user/foo.rb现在我正在使用一个定义了自己的Foo类的库。我收到此错误:warning:toplevelconstantFooreferencedbyUser::FooUser仅引用具有完整路径的Foo,User::Foo,而Foo实际上从来没有指的是Foo。这是怎么回事?更新:才想起我之前遇到过同样的问题,在问题1中看到这里:HowdoIrefertoasubmodule's"fullpath"inruby? 最佳答案
我想通过JSON获取Wikiquote页面的结构化版本(基本上我需要所有短语)示例:http://en.wikiquote.org/wiki/Fight_Club_(film)我试过:http://en.wikiquote.org/w/api.php?format=xml&action=parse&page=Fight_Club_(film)&prop=text但我得到了所有HTML源代码。我需要每个pharse作为数组的一个元素我如何使用DBPEDIA实现这一目标? 最佳答案 首先,我不确定您是否可以使用DBpedia查询wiki
有没有办法让我的en.yml文件包含一个常量?#en.ymlfoo:bar:IloveBAZsomuch!#initializers/constants.rbBAZ="stackoverflow.com"I18n.t("foo.bar")->"Ilovestackoverflow.comsomuch!"?如果没有,有没有办法自己引用yaml文件?foo:bar:Ilove*baz*somuch!baz:stackoverflow.comI18n.t("foo.bar")->"Ilovestackoverflow.comsomuch!" 最佳答案