value...),array(key=>value...)....)"."/> value...),array(key=>value...)....)".">
Home > Article > Backend Development > How to write a two-dimensional array in php
php How to write a two-dimensional array: 1. Direct assignment method, syntax "$array[one-dimensional subscript][two-dimensional subscript]="value";"; 2. Use the array() function, Syntax "array(array(key=>value...),array(key=>value...)....)".
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
two-dimensional array
The two-dimensional array is declared in the same way as the one-dimensional array, except that one or more elements in the array are also declared as an array. There are also two declarations: directly assigning values to the array elements and using the array() function. 2 Dimensional array methods.
The following uses the method of directly assigning values to the array elements to declare an array. The sample code is as follows:
<?php $array[0]['name'] = 'zhangsan'; $array[0]['chinese'] = '89'; $array[0]['math'] = '95'; $array[0]['english'] = '88'; $array[1]['name'] = 'lisi'; $array[1]['chinese'] = '91'; $array[1]['math'] = '86'; $array[1]['english'] = '90'; echo '<pre class="brush:php;toolbar:false">'; print_r($array); ?>
The running results are as follows:
Array ( [0] => Array ( [name] => zhangsan [chinese] => 89 [math] => 95 [english] => 88 ) [1] => Array ( [name] => lisi [chinese] => 91 [math] => 86 [english] => 90 ) )
Use the array() function to declare a two-dimensional Arrays are similar to declaring one-dimensional arrays. The sample code is as follows: (The following code is equivalent to the above code, and the running results are the same)
<?php $array = array( array('name'=>'zhangsan','chinese'=>'89','math'=>'95','english'=>'88'), array('name'=>'lisi','chinese'=>'91','math'=>'86','english'=>'90') ); echo '<pre class="brush:php;toolbar:false">'; print_r($array); ?>
Similarly, getting the elements in the two-dimensional array is also the same as the one-dimensional array Similarly, you only need to indicate the subscript of each dimension. The sample code is as follows:
<?php $array = array( array('name'=>'zhangsan','chinese'=>'89','math'=>'95','english'=>'88'), array('name'=>'lisi','chinese'=>'91','math'=>'86','english'=>'90') ); echo $array[0]['name'].'同学的数学考了'.$array[0]['math'].'分'; ?>
The running results are as follows:
zhangsan同学的数学考了95分
Tip: Different dimensions of the array indicate how many dimensions we need to use Subscript (index) is used to obtain the corresponding array element. For example, a two-dimensional array requires two subscripts to obtain the corresponding array element, a three-dimensional array requires three, and so on.
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to write a two-dimensional array in php. For more information, please follow other related articles on the PHP Chinese website!