foreach 两层改变原值,请大神赐教
程序员文章站
2024-01-09 15:00:16
...
如下要怎么做
$data = [1,2,3,[a,b,c]];
foreach($data as &$e){
//$data数组里的数量不确定,一维数组各加1,二维数组各拼接m
}
var_dump($data);//[2,3,4,[am,bm,cm]]
unset($e);
回复内容:
如下要怎么做
$data = [1,2,3,[a,b,c]];
foreach($data as &$e){
//$data数组里的数量不确定,一维数组各加1,二维数组各拼接m
}
var_dump($data);//[2,3,4,[am,bm,cm]]
unset($e);
$data = [1,2,3,['a','b','c']];
foreach($data as &$e){
//$data数组里的数量不确定,一维数组各加1,二维数组各拼接m
if(is_array($e)){
foreach ($e as $k => &$v) {
$v = $v.'m';
}
}else{
$e = $e + 1;
}
}
print_r($data);//[2,3,4,[am,bm,cm]]
&$value) {
if(is_array($value)){
foreach($value as &$v){
$v.= 'm';
}
} else {
++$value;
}
}
}
$array = array(1, 2, 3, array('a', 'b', 'c'));
test($array);
print_r($array);
运行结果如下:
Array
(
[0] => 2
[1] => 3
[2] => 4
[3] => Array
(
[0] => am
[1] => bm
[2] => cm
)
)