PHP development basic tutorial multi-dimensional array

1. PHP two-dimensional array

In the primary tutorial, the arrays we learn are all one-dimensional arrays

In this chapter we introduce Multi-dimensional arrays, starting with two dimensions

The values ​​in one array can be another array, and the values ​​in another array can also be an array. In this way, we can create a two-dimensional g array:

Create a two-dimensional array as follows:

Example: The code is as follows

<?php
// 二维数组:
$cars = array
(
    array("Volvo",100,96),
    array("BMW",60,59),
    array("Toyota",110,100)
);
?>

II , PHP multidimensional array

A multidimensional array is an array containing one or more arrays.

In a multi-dimensional array, each element in the main array can also be an array, and each element in the sub-array can also be an array.

Example: We created a multi-dimensional array that automatically assigns ID keys. The code is as follows

<?php 
$sites = array 
( 
    "php"=>array 
    ( 
        "php中文网", 
        "http://www.php.cn" 
    ), 
    "google"=>array 
    ( 
        "baidu 搜索", 
        "http://www.baidu.com" 
    ), 
    "taobao"=>array 
    ( 
        "淘宝", 
        "http://www.taobao.com" 
    ) 
); 
print("<pre>"); // 格式化输出数组 
print_r($sites); //将数组打印出来
print("</pre>"); 
?>

The output result is as shown on the right

Try to output a single element on the page :

The code is as follows

<?php 
$sites = array 
( 
    "php"=>array 
    ( 
        "php中文网", 
        "http://www.php.cn" 
    ), 
    "baidu"=>array 
    ( 
        "baidu 搜索", 
        "http://www.baidu.com" 
    ), 
    "taobao"=>array 
    ( 
        "淘宝", 
        "http://www.taobao.com" 
    ) 
); 
echo '欢迎访问'.$sites['php'][0].'我们的网址是'.$sites['php'][1]
?>

The output result is shown on the right
Note: When creating a multi-dimensional array, pay attention to the commas separating the arrays. The outer array ")" is followed by a semicolon.


Continuing Learning
||
<?php // 二维数组: $cars = array ( array("Volvo",100,96), array("BMW",60,59), array("Toyota",110,100) ); ?>
submitReset Code