How to iterate through a two-dimensional array in PHP?

In PHP, you can use a foreach loop to iterate over two-dimensional array data.

Here is an example code for traversing a two-dimensional array:

$array = array(
    array("name" => "John", "age" => 25),
    array("name" => "Jane", "age" => 30),
    array("name" => "Tom", "age" => 35)
);

// 遍历二维数组
foreach ($array as $row) {
    foreach ($row as $key => $value) {
        echo $key . ": " . $value . "<br>";
    }
    echo "<br>";
}

In this example, $array is a two-dimensional array containing three subarrays, with each subarray representing the information of a person. Two nested foreach loops are used, with the first loop iterating over each subarray and the second loop iterating over each key-value pair within each subarray.

The output is:

name: John
age: 25

name: Jane
age: 30

name: Tom
age: 35

By iterating through a two-dimensional array, one can access the key and value of each element, allowing for further processing of the data within the array.

bannerAds