PHP multidimens...LOGIN

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

## Xiao Ming Xiaolong## 小花 9 95 94

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:

<?php
header("Content-type:text/html;charset=utf-8");
$arr=array(
    array("小明","90","80","77"),
    array("小龙","88","75","89"),
    array("小花","99","95","94"),
);
echo $arr[0][0]."---语文:".$arr[0][1].":数学:".$arr[0][2].":英语:".$arr[0][3]."<br>";
echo $arr[1][0]."---语文:".$arr[1][1].":数学:".$arr[1][2].":英语:".$arr[1][3]."<br>";
echo $arr[2][0]."---语文:".$arr[2][1].":数学:".$arr[2][2].":英语:".$arr[2][3]."<br>";
?>

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

<?php
header("Content-type:text/html;charset=utf-8");
$arr=array(
    array("小明","90","80","77"),
    array("小龙","88","75","89"),
    array("小花","99","95","94"),
);
for($x=0;$x<3;$x++){
    echo "<p>行数$x</p>";
    echo"<ul>";
    for($row=0;$row<3;$row++){
        echo "<li>".$arr[$x][$row]."</li>";
    }
    echo"</ul>";
}
?>

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

<?php
$name=array(
    array(
        array('tom','andy','jack'),
       array('row','laya','lis')
    ),
);
print_r($name[0][1][1]);
?>

Program running result:

laya



Next Section

<?php header("Content-type:text/html;charset=utf-8"); $arr=array( array("小明","90","80","77"), array("小龙","88","75","89"), array("小花","99","95","94"), ); for($x=0;$x<3;$x++){ echo "<p>行数$x</p>"; echo"<ul>"; for($row=0;$row<3;$row++){ echo "<li>".$arr[$x][$row]."</li>"; } echo"</ul>"; } ?>
submitReset Code
ChapterCourseware
    None
Name## Language
Mathematics English

90
80 77
88 75 89