PHP foreach 和引用

Lee*_*Lee 3 php arrays foreach reference

我试图在 PHP 中的嵌套 foreach 循环中使用指针修改值.. 然而,以下行似乎不起作用:

// Assign a the attribs value to the array
$link_row['value'] = $args[ $u_value ];
Run Code Online (Sandbox Code Playgroud)

变量 $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] );
              }
           }
        }
     }
  }
Run Code Online (Sandbox Code Playgroud)

f.a*_*ian 6

必须使用他们在一个尚未设定的变量之后foreach。即使你有两个foreach(..)陈述,一个接一个。即使你有一个foreach(..)里面另一个foreach(..)没有例外!

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
Run Code Online (Sandbox Code Playgroud)

这是不久前搞砸了一个大项目的另一段有趣的代码:

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;
}
Run Code Online (Sandbox Code Playgroud)

事实上,有人unset($line)在第一个之后foreach(..)确实弄乱了数组中的数据,因为它&$line是一个引用,而第二个foreach(..)在循环遍历数据时为其分配了不同的值,并且它不断覆盖最后一行数据。