作为一名C++程序员,在转做PHP开发的过程中,对PHP数组产生了一些混淆,与C++数组有相似的地方,也有一些不同,下面就全面地分析一下PHP的数组及其与C++中相应数据类型的区别和联系。
数组的分类:
1、数值数组:也叫索引数组,即以数字(从0 开始)作为数组下标。相当于C++中的vector。
2、关联数组:以字符串作为数组下标。相当于C++中的map。
3、多维数组:数组中每个元素也是一个数组。其子数组中的每个元素也可以是数组。
数组的声明:
1、数值数组
a、如下例子中,会自动分配数字ID键。
$names = array("Peter","Joe","Lily");
b、如下例子中,我们人工分配数字ID键。
$names[0] = "Peter";
$names[1] = "Joe";
$names[2] = "Lily";
可以在脚本中使用这些ID键:
1
2
3
4
5
6
7
|
<?php $names [0] = "Peter" ; $names [1] = "Joe" ; $names [2] = "Lily" ; echo $names [0]. " and " . $names [1]. " are " . $names [2]. "'s neighbors" ; /* 何问起 hovertree.com */ ?> |
2、关联数组:
例子1
$ages = array("Peter"=>32, "Joe"=>30, "Lily"=>28);
例子2
本例与例子1相同,只是另一种创建数组的方法。
1
2
3
|
$ages [ "Peter" ] = "32" ; $ages [ "Joe" ] = "30" ; $ages [ "Lily" ] = "28" ; |
在脚本中使用关联数组:
1
2
3
4
5
6
7
|
<?php $ages [ "Peter" ] = "32" ; $ages [ "Joe" ] = "30" ; $ages [ "Lily" ] = "28" ; echo "Peter is " . $ages [ "Peter" ]. " years old." ; /* 何问起 hovertree.com */ ?> |
以上脚本输出:
Peter is 32 years old.
3、多维数组:
在本例中,我们创建了一个带有自动分配数字ID键的多维数组:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
$families = array { "Griffin" => array { "Peter" , "Lois" , "Megan" }, "Quagmire" => array { "Glenn" }, "Brown" => array { "Cleveland" , "Loretta" , "Junior" } }; echo "Is " . $families [ 'Griffin' ][2] . " a part of the Griffin family?" ; |
以上代码输出:
Is Megan a part of the Griffin family?
1、for循环遍历
for循环只能遍历索引数组。
1
2
3
4
5
6
7
|
<?php $names = array ( "Peter" , "Joe" , "Lily" ); for ( $id =0; $id < count ( $names );++ $id ) { echo $names [ $id ]; } ?> |
2、foreach遍历
即可以遍历索引数组,也可以遍历关联数组
遍历索引数组
1
2
3
4
5
6
7
8
9
|
foreach (array_expression as $value ) { 循环体; } 遍历关联数组 foreach (array_expression as $key => $value ) { 循环体; } |
A、一维数组遍历
索引数组
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
<?php $contact = array ( "李某" , "xx公司" , "abc@xx.com" ); foreach ( $contact as $value ) { echo $value ; } ?> <?php $contact = array ( "姓名" => "李某" , "公司" => "xx公司" , "邮箱" => "abc@xx.com" ); foreach ( $contact as $key => $value ) { echo $key . ":" . $value ; } ?> |
B、多维数组遍历
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
<?php $wage = array ( "市场部" = array ( array (1, "李某" , "市场经理" ,8000), array (2, "王某" , "市场专员" ,5000), array (3, "刘某" , "市场专员" ,7000) ), "产品部" = array ( array (1, "李某" , "产品经理" ,9000), array (2, "王某" , "产品专员" ,6000), array (3, "刘某" , "产品专员" ,5000) ), "账务部" = array ( array (1, "李某" , "账务经理" ,7000), array (2, "王某" , "账务专员" ,6000), array (3, "刘某" , "账务专员" ,5000) ) ); foreach ( $wage as $section => $table ) { echo $section . "部门人员如下" ; foreach ( $table as $row ) { foreach ( $row as $value ) { echo $value ; } } } /* 何问起 hovertree.com */ ?> |
以上所述是小编给大家介绍的php数组的实例详解,希望对大家有所帮助。