我一定不知道如何处理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的更改似乎都会丢失。我做错了什么?
答案 0 :(得分:1)
如果要在foreach语句中更改数组项,则应通过引用传递。
foreach ($ary as $key => &$vals) {
}
答案 1 :(得分:0)
<?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>";
?>