2013-04-04 106 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