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

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

4

1 回答 1

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";
    }
}
于 2013-04-04T10:03:33.753 回答