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