我想知道为什么这段代码会这样工作。为什么更改变量名称会有所不同?$t不应该只在foreach范围内可用吗?
$types = [
['name'=>'One'],
['name'=>'Two']
];
foreach($types as &$t){
if ($t['name']=='Two') $t['selected'] = true;
}
// now put that selection to top of the array
// I know this is not a good way to sort, but that's not the point
$_tmp=[];
// Version 1
// foreach($types as $v) if (isset($v['selected'])) $_tmp[] = $v;
// foreach($types as $v) if (!isset($v['selected'])) $_tmp[] = $v;
// Version 2
foreach($types as $t) if (isset($t['selected'])) $_tmp[] = $t;
foreach($types as $t) if (!isset($t['selected'])) $_tmp[] = $t;
print_r($_tmp);
//Version 1 : Array ( [0] => Array ( [name] => Two [selected] => 1 ) [1] => Array ( [name] => One ) )
//Version 2 : Array ( [0] => Array ( [name] => One ) [1] => Array ( [name] => One ) )
正确答案在问题注释中。"一旦你在php中声明了变量,它将一直可用到脚本结束。同样的事情也适用于在for和Foreach循环中声明的变量。这些变量在脚本结束前也可用。因此,在你的情况下,Foreach循环中$t中存储的最后一个值将在脚本的其余部分可用。–Gokul Shinde Mar 31 at 9:33"
由于,您正在使用引用运算符(&)
$types = array(
0 => array('name'=>'One'),
1 => array('name'=>'Two'));
阵列转换为
$types = array(
0 => array('name'=>'One'),
1=> array('name'=>'Two', 'selected' => 1);
foreach($types as $t){
if ($t['name']=='Two') $t['selected'] = true;}
如果删除&对于每个选定的键,将不会从$types数组中反映出来。