Home  >  Article  >  Backend Development  >  How to understand foreach traversing a two-dimensional array in php

How to understand foreach traversing a two-dimensional array in php

autoload
autoloadOriginal
2021-05-08 14:40:334817browse

phpIt is often necessary to use the traversal of two-dimensional array. Many people understand the traversal of one-dimensional array, but for the traversal of two-dimensional array The understanding of traversal means there is nothing you can do. This article will take you to take a look at it.

First of all, if you want to understand the traversal of a two-dimensional array, you must first understand the principle of traversal of a one-dimensional array. Without further ado, let’s go directly to the code.

Two ways to traverse a one-dimensional array:

1. Need to operate on the keys and values ​​of the array

<?php
$arr=array(&#39;a&#39;=>&#39;php&#39;,&#39;c&#39;=>&#39;.cn&#39;);
foreach($arr as $key=>$value){
    echo $key.&#39;=>&#39;.$value."<br>";
}
输出:a=>php
      c=>.cn

2. Need to operate on the keys and values ​​of the array Operation

<?php
$arr2=array(&#39;d&#39;=>&#39;ok&#39;,&#39;b&#39;=>&#39;oya&#39;);
foreach($arr2 as $value){
    echo $value."<br>";
}
输出:  ok
        oya

The traversal of a one-dimensional array is actually the internal pointer of foreach constantly pointing to the next key-value pair. If the pointer is empty, it is restored to the original pointer. Every time you point to a key-value pair, you can operate on the key-value pair inside foreach.

Then let’s take a look at the traversal of the two-dimensional array:

<?php
$arr3=[[3,0,9],[7,8,3],[1,8,2]];
foreach($arr3 as $key=>$value){
    foreach($value as $k=>$v){
        echo &#39;这是二维数组中索引为:&#39;.$key.&#39;的一维数组的第&#39;.$k.&#39;个,值为:&#39;.$v.&#39;<br>&#39;;
    }
    echo "<br>";
}
?>
输出:
这是二维数组中索引为:0的一维数组的第0个,值为:3
这是二维数组中索引为:0的一维数组的第1个,值为:0
这是二维数组中索引为:0的一维数组的第2个,值为:9

这是二维数组中索引为:1的一维数组的第0个,值为:7
这是二维数组中索引为:1的一维数组的第1个,值为:8
这是二维数组中索引为:1的一维数组的第2个,值为:3

这是二维数组中索引为:2的一维数组的第0个,值为:1
这是二维数组中索引为:2的一维数组的第1个,值为:8
这是二维数组中索引为:2的一维数组的第2个,值为:2

In fact, the traversal of the two-dimensional array is to treat the array inside the two-dimensional array as a Variable, use foreach() again to traverse the array we treat as a variable.

Recommended: 2021 PHP interview questions summary (collection)》《php video tutorial

The above is the detailed content of How to understand foreach traversing a two-dimensional array in php. For more information, please follow other related articles on the PHP Chinese website!

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