php foreach作为变量

use*_*850 3 php foreach

我想使用foreach循环遍历数组列表并向每个数组添加一个元素.

$tom = array('aa','bb','cc');
$sally = array('xx','yy','zz');

$myArrays = array('tom','sally');

 foreach($myArrays as $arrayName) {
     ${$arrayName}[] = 'newElement';
 }
Run Code Online (Sandbox Code Playgroud)

使用$ {$ arrayName} []是最好的方法吗?还有其他选择而不是使用花括号吗?它目前有效,但我只是想知道是否有更好的选择.

谢谢

Tom*_*lak 9

使用参考.

$myArrays = array(&$tom, &$sally);

foreach($myArrays as &$arr) {
  $arr[] = 'newElement';
}
Run Code Online (Sandbox Code Playgroud)


Tes*_*rex 5

如果你坚持这种结构,我会坚持你在那里做的事情.但评论可能会很好.

如果你可以重新排列东西,为什么不嵌套呢?

$tom = array('aa','bb','cc');
$sally = array('xx','yy','zz');

$myArrays = array(&$tom, &$sally); // store the actual arrays, not names

// note the & for reference, this lets you modify the original array inside the loop
foreach($myArrays as &$array) {
    $array[] = 'newElement';
}
Run Code Online (Sandbox Code Playgroud)