2013-04-04 43 views
0

我有一个穆蒂,渔政船阵列像这样:设置元素值未正常工作

$arrayTest = array(0=>array("label"=>"test","category"=>"test","content"=>array(0=>array("label"=>"test","category"=>"test"),1=>array("label"=>"test","category"=>"test")))); 

然后我想设置的所有标签内容阵列像这样:

foreach($arrayTest as $obj) { 
    foreach($obj["content"] as $anobj){ 
     $anobj["label"] = "hello"; 
    } 
} 

之后,我打印出来的阵列

echo json_encode($arrayTest); 

在我看到浏览器:

[{"label":"test","category":"test","content":[{"label":"test","category":"test"},{"label":"test","category":"test"}]}] 

没有什么改变,但如果我尝试

$arrayTest[0]["content"][0]["label"] = "hello"; 
$arrayTest[0]["content"][1]["label"] = "hello"; 

然后好像工作。我想知道为什么第一种方法不起作用?

+1

从手动:[“为了能够直接修改循环中的数组元素,在$值前加上&。在这种情况下,值将由引用赋值。”](http://php.net/manual/control-structures .foreach.php) – Yoshi 2013-04-04 10:03:20

+0

感谢您的帮助! :) – 2013-04-04 10:08:47

回答

1

你需要参考迭代这个数组的变化要坚持:

foreach($arrayTest as &$obj) { // by reference 
    foreach($obj["content"] as &$anobj){ // by reference 
     $anobj["label"] = "hello"; 
    } 
} 

// Whenever you iterate by reference it's a good idea to unset the variables 
// when finished, because assigning to them again will have unexpected results. 
unset($obj); 
unset($anobj); 

或者,您可以索引数组使用键,从根开始:

foreach($arrayTest as $key1 => $obj) { 
    foreach($obj["content"] as $key2 => $anobj){ 
     $arrayTest[$key1]["content"][$key2]["label"] = "hello"; 
    } 
} 
+0

很酷的作品,谢谢!我会在10分钟后接受你的回答:)因为系统限制 – 2013-04-04 10:06:38