Home > Backend Development > PHP Tutorial > foreach 两层改变原值,请大神赐教

foreach 两层改变原值,请大神赐教

WBOY
Release: 2016-06-06 20:12:27
Original
948 people have browsed it

如下要怎么做

<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>
Copy after login
Copy after login

回复内容:

如下要怎么做

<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>
Copy after login
Copy after login

<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>
Copy after login

<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>
Copy after login

运行结果如下:
Array
(

<code>[0] => 2
[1] => 3
[2] => 4
[3] => Array
    (
        [0] => am
        [1] => bm
        [2] => cm
    )
</code>
Copy after login

)

<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>
Copy after login
Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template