PHP foreach:替换嵌套数组中的值

Dan*_*son 0 php arrays

我想将'value2'更改为'My string'.我知道这可以通过使用数组键,但我想知道它是否更清洁.

$nested_array[] = array('value1', 'value2', 'value3');

foreach($nested_array as $values){

    foreach($values as $value){

        if($value == 'value2'){
            $value = 'My string';
        }

    }

}
Run Code Online (Sandbox Code Playgroud)

Mar*_*rio 6

只需使用引用运算符&通过引用传递值:

foreach($nested_array as &$values) {
    foreach($values as &$value) {
        do_something($value);
    }
}
unset($values); // These two lines are completely optional, especially when using the loop inside a
unset($value);  // small/closed function, but this avoids accidently modifying elements later on.
Run Code Online (Sandbox Code Playgroud)

  • 你不应该忘记在循环之后`unset($ value)` - 否则在你的代码中访问该变量可能会产生意想不到的副作用. (2认同)