我一定错过了PHP数组的处理方式。当我执行以下代码时:
<?php
$ary = array(
"alpha" => array("A"=>1,"B"=>2,"C"=>3),
"beta" => array("A"=>7,"B"=>8,"C"=>9)
);
foreach ($ary as $key => $vals) {
$vals["B"]=99;
echo $key."= ".$vals["A"]." ".$vals["B"]." ".$vals["C"]."<br>";
}
echo $ary['alpha']["B"]."<br>";
?>
我:
alpha= 1 99 3
beta= 7 99 9
2
每种情况下99的变化似乎都丢失了。我做错了什么?
如果你想在foreach语句中改变数组的项,你应该通过引用传递。
foreach ($ary as $key => &$vals) {
}
<?php
$ary = array(
"alpha" => array("A"=>1,"B"=>2,"C"=>3),
"beta" => array("A"=>7,"B"=>8,"C"=>9)
);
foreach ($ary as $key => $vals) {
//$vals["B"]= 99;
$ary[$key]["B"] = 99;
echo $key."= ".$vals["A"]." ".$vals["B"]." ".$vals["C"]."<br>";
}
echo $ary['alpha']["B"]."<br>";
?>