php数组遍历

WBOY
WBOYOriginal
2016-07-29 09:06:38953Durchsuche

1.一维数组遍历

<code><span>foreach</span>(<span>$array</span><span>as</span><span>$value</span>){
    <span>echo</span><span>$value</span>;
}</code>

2.二维数组遍历

<code><span>foreach</span>(<span>$array</span><span>$key</span>=><span>$val</span>){
    <span>echo</span><span>$key</span>.<span>'=>'</span>.<span>$val</span>;
}</code>

3.多维数组遍历

<code><span>public</span><span>static</span><span><span>function</span><span>multi_arr_foreach</span><span>(<span>$arr</span>)</span> {</span><span>static</span><span>$data</span>; 
    <span>if</span> (!is_array (<span>$arr</span>)) {
        <span>return</span><span>$data</span>;
    }
    <span>foreach</span> (<span>$arr</span><span>as</span><span>$key</span> => <span>$val</span> ) {
        <span>if</span> (is_array (<span>$val</span>)) {
            <span>self</span>::multi_arr_foreach(<span>$val</span>);
        } <span>else</span> {
            <span>$data</span>[]=<span>$val</span>;
        }
    }
    <span>return</span><span>$data</span>;
}</code>

不过还看到一个很简短的写法,还不是很理解

<code><span><span>function</span><span>loop_array</span><span>(<span>$arr</span>)</span>{</span><span>$value</span> = is_array(<span>$arr</span>) ? array_map(<span>'loop_array'</span>,<span>$arr</span>) : <span>$arr</span>;
<span>return</span><span>$value</span>;
}</code>

在遍历三维数组时,如果要修改value值时,要注意还要把改变的value值再赋给key

<code><span><span>function</span><span>threeArray</span><span>(<span>$arr</span>)</span>{</span><span>foreach</span> (<span>$arr</span><span>as</span><span>$key</span> => <span>$value</span>) {     
            <span>$value</span>[<span>'4'</span>] = <span>'very'</span><span>$arr</span>[<span>$key</span>] = <span>$value</span>;
        }
        <span>return</span><span>$arr</span>;
    }</code>
').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i ').text(i)); }; $numbering.fadeIn(1700); }); });

以上就介绍了php数组遍历,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn