PHP foreach:替换嵌套数组中的值
我想将'value2'更改为'My string'。我知道这是可能的使用数组键,但我想知道这是否是一个更干净的方式PHP foreach:替换嵌套数组中的值,php,arrays,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';
$nested_array[] = array('value1', 'value2', 'value3');
foreach($nested_array as $values){
foreach($values as $value){
if($value == 'value2'){
$value = 'My string';
}
}
}
只需使用引用运算符
&
通过引用传递值:
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.
函数strereplaceassoc(数组$replace,$subject){
返回str_replace(数组_键($replace)、数组_值($replace)、$subject);
}
$nested_array[]=数组('value1','value2','value3');
foreach($嵌套数组作为$值){
foreach($value作为$value){
$replace=数组(
“value2”=>“我的字符串”
);
$new_values=strReplaceAssoc($replace,$value);
回显$new_值。“
”;
}
}
您正在搜索的是PHP函数数组
$key = array_search('value2', $nested_array);
$nested_array[$key] = 'My String';
此解决方案比在整个数组中迭代性能更好。使用数组键:
$nested_array = array();
$nested_array[] = array('value1', 'value2', 'value3');
foreach($nested_array as $key => $values){
foreach($values as $key2 => $value){
if($value == 'value2'){
$nested_array[$key][$key2] = 'My string';
}
}
}
var_export($nested_array);
// array ( 0 => array ( 0 => 'value1', 1 => 'My string', 2 => 'value3', ), )
您还可以为此使用:
array_walk_recursive($nested_array,
function(&$v) {
if ($v == 'value2') $v = 'My string';
}
);
这适用于任何级别的嵌套,您无需记住在之后取消设置任何内容。虽然这可能适用于给定的示例,但您应该记住,修改正在迭代的数组是个坏主意。尤其是在添加/删除项目时。不要忘记在循环后取消设置($value),否则在代码中访问该变量可能会产生意外的副作用。只要只修改值,就可以节省大量的时间。改变数组本身是不同的,但是不管你使用哪种循环,都必须考虑这些因素。如果你想要100%安全的话,是的,在例子中加上这两条线。是的,我理解你,在这两种情况下你都需要它,否则你会再创建一个拷贝(至少在那个级别上)。因此,您不会修改原始值。这对嵌套数组没有帮助,因为您需要添加某种递归以支持无限深度。您的示例将失败,因为$nested_数组包含一个值数组,而不是值数组。好的。。。对于嵌套数组,可以在php中使用SPL deliverd的RecursiveArrayIterator对象。在上查找第二条用户评论。这将以非常聪明的方式解决您的问题。
array_walk_recursive($nested_array,
function(&$v) {
if ($v == 'value2') $v = 'My string';
}
);