PHP multidimensional array

In the previous tutorial, we have learned that an array is a simple list of numbers/values.

Sometimes we want to use more than one key to save data, so we need to use PHP's multi-dimensional array to achieve it.


Basic knowledge

##PHP multidimensional array refers to a More than one array

PHP can understand it as a multi-dimensional array of two, three, four or five levels or even more levels. However, most people have trouble managing arrays that are more than three levels deep

Note: The dimension of the array indicates the index number of elements that need to be selected

php two-dimensional array

A two-dimensional array is an array of arrays. Similarly, a three-dimensional array is an array of arrays.

Note:A two-dimensional array requires two indexes to select elements

Example

Suppose there is a score sheet

We can save the array in the above table in a two-dimensional array,

$arr=array(
array("Xiao Ming" ,"90","80","77"),
array("小龙","88","75","89"),
array("小花","99"," 95","94"),
);

Use the code to output the result:

"; echo $arr[1][0]."---语文:".$arr[1][1].":数学:".$arr[1][2].":英语:".$arr[1][3]."
"; echo $arr[2][0]."---语文:".$arr[2][1].":数学:".$arr[2][2].":英语:".$arr[2][3]."
"; ?>

The program running result:

Xiaoming---Chinese: 90: Mathematics: 80: English: 77
Xiaolong---Chinese: 88: Mathematics: 75: English: 89
Xiaohua---Chinese: 99: Mathematics: 95: English: 94


We can also use another for loop inside a for loop to get the elements in the array

Example

行数$x

"; echo"
    "; for($row=0;$row<3;$row++){ echo "
  • ".$arr[$x][$row]."
  • "; } echo"
"; } ?>

Program running result:

Number of lines 0
• Xiao Ming
• 90
• 80
Line number 1
• Xiaolong
• 88
• 75
Line number 2
• Xiaohua
• 99
• 95


##PHP three-dimensional array

Note:Two-dimensional array requires two indexes to select elements

Example

Program running result:

laya



Continuing Learning

About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!
## Xiao Ming Xiaolong ## 小花 9 95 94
||
行数$x

"; echo"
    "; for($row=0;$row<3;$row++){ echo "
  • ".$arr[$x][$row]."
  • "; } echo"
"; } ?>
submit Reset Code
Name ## Language
Mathematics English

90
80 77
88 75 89