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

时间:2013-04-04 10:01:02

标签: php

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

$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 个答案:

答案 0 :(得分: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";
    }
}