简体   繁体   English

php foreach数组并分配此数组

[英]php foreach over an array and assignment of this array

I want to add a value to an array while foreaching it : 我想在预处理时为数组添加一个值:

foreach ($array as $cell) {
    if ($cell["type"] == "type_list") {
        $cell["list"] = $anObject;
        error_log(print_r($cell, TRUE), 0);
}
error_log(print_r($array, TRUE), 0);

The first printr is ok but the object added disapear when I leave the loop ant print the array. 第一个printr是好的,但是当我离开循环时,对象添加了disape,打印出数组。

I guess this is a normal behaviour, what is the best way to work around this "feature" ? 我想这是一种正常的行为,解决这个“功能”的最佳方法是什么?

Just call $cell by reference like this: 只需通过引用调用$cell ,如下所示:

foreach($array as &$cell) {...}

And it should retain the value. 它应该保留价值。 Passing by reference . 通过引用传递

When you iterate over the array, $cell is a copy of the value, not a reference so changing it will not effect the value in the array. 迭代数组时, $cell是值的副本,而不是引用,因此更改它不会影响数组中的值。

You should either use & to make the $cell a reference: 您应该使用&来使$cell成为引用:

foreach ($array as &$cell) {
    if ($cell["type"] == "type_list") {
        $cell["list"] = $anObject;
        error_log(print_r($cell, TRUE), 0);
}
error_log(print_r($array, TRUE), 0);

Or access the array items directly using an index. 或者使用索引直接访问数组项。

foreach ($array as $i => $cell) {
    if ($array[$i]["type"] == "type_list") {
        $array[$i]["list"] = $anObject;
        error_log(print_r($array[$i], TRUE), 0);
}
error_log(print_r($array, TRUE), 0);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM