Home  >  Article  >  Backend Development  >  How to output associated two-dimensional array in php

How to output associated two-dimensional array in php

PHPz
PHPzOriginal
2023-04-23 10:08:03450browse

In PHP, array is a very useful data type, which provides an effective way to help developers process data. Among them, associative array is one of the very common array types, which is very convenient when processing data. An associative two-dimensional array refers to one that contains multiple sub-arrays, and each sub-array contains multiple elements, and each element has its own unique key value. In PHP, to output an associated two-dimensional array, we can use the foreach statement to loop through, access the elements of each subarray through key-value pairs, and output them to the page.

The key code is as follows:

//定义一个关联二维数组
$students = array(
  array("name" => "小明", "age" => 18, "sex" => "男"),
  array("name" => "小红", "age" => 20, "sex" => "女"),
  array("name" => "小亮", "age" => 22, "sex" => "男")
);

//循环遍历输出子数组的内容
foreach($students as $student) {
  echo "姓名:" . $student['name'] . ", 年龄:" . $student['age'] . ", 性别:" . $student['sex'] . "<br>";
}

The above code first defines an associative two-dimensional array. Each sub-array contains elements corresponding to the three key values ​​of name, age and gender. Next, use the foreach loop statement to traverse the $students array, obtain the elements in each sub-array, and use $student['name'], $student['age'] and $student['sex']The values ​​corresponding to the key values ​​are output to the page respectively.

Run the above code, the page will output the following content, showing the element information in each sub-array:

姓名:小明, 年龄:18, 性别:男
姓名:小红, 年龄:20, 性别:女
姓名:小亮, 年龄:22, 性别:男

As can be seen from the above code, it is very easy to output associated two-dimensional arrays in PHP element information. In actual application scenarios, developers can use array-related functions and statements for data processing according to specific needs. At the same time, you need to pay attention to using appropriate loop statements and the syntax format corresponding to key values ​​to correctly output the contents of the associated two-dimensional array.

The above is the detailed content of How to output associated 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