使用foreach设置元素值时没有按预期工作



我有一个像这样的多维数组:

$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";

那么它似乎有效。我想知道为什么第一种方法不起作用?

您需要通过引用迭代数组以使更改保持不变:

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";
    }
}

最新更新