Home >Backend Development >PHP Tutorial >php array traversal

php array traversal

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-07-29 09:06:38964browse

1. One-dimensional array traversal

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

2. Two-dimensional array traversal

<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. Multi-dimensional array traversal

<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>

But I also saw a very short way of writing it, and I don’t quite understand it yet

<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>

When traversing a three-dimensional array , if you want to modify the value, be careful to assign the changed value to the 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); }); });

The above has introduced PHP array traversal, including aspects of it. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
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