Heim >Backend-Entwicklung >PHP-Tutorial >foreach 两层改变原值,请大神赐教
如下要怎么做
<code>$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);</code>
如下要怎么做
<code>$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);</code>
<code>$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]]</code>
<code><?php function test(&$array){ foreach ($array as $key => &$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);</code>
运行结果如下:
Array
(
<code>[0] => 2 [1] => 3 [2] => 4 [3] => Array ( [0] => am [1] => bm [2] => cm ) </code>
)
<code><?php $data = [1,2,3,['a','b','c']]; foreach($data as &$v){ if(is_array($v)){ foreach ($v as &$av) { $av .= 'm'; } }else if(is_numbric($v)){ ++$v; } } print_r($data);//[2,3,4,[am,bm,cm]]</code></code>