Home > Backend Development > PHP Tutorial > php array traversal

php array traversal

WBOY
Release: 2016-07-29 09:06:38
Original
951 people have browsed it

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

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

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

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

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>
Copy after login
').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.

Related labels:
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