php数组

数组

数组是一个能在单个变量中存储多个值的特殊变量。

创建变量方法

1
array()

创建数值数组

自动分配id键

1
2
3
4
5
6
7
<?php 
$cars=array("Volvo","BMW","Toyota");
echo "I like".$cars[0].",".$cars[1]."and".$cars[2].".";
?>

/*输出结果:
I likeVolvo,BMWandToyota.

人工分配id键

1
2
3
4
5
6
7
8
9
10
<?php 
$cars=array("Volvo","BMW","Toyota");
$cars[1]="Volvo";
$cars[2]="BMW";
$cars[3]="Toyota";
echo "I like".$cars[1].",".$cars[2]."and".$cars[3].".";
?>

/*输出结果:
I likeVolvo,BMWandToyota.

获取数组的长度

1
2
3
4
5
6
<?php 
$cars=array("Volvo","BMW","Toyota");
echo count($cars); #count()函数用于返回数组的长度(元素的数量)
?>

/*输出结果:3

遍历数值数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php 
$cars=array("Volvo","BMW","Toyota");
$arrlength=count($cars);

for($x=0;$x<$arrlength;$x++) #arrlength=array().length
{
echo $cars[$x];
echo "<br>";
}
?>

/*输出结果:
Volvo
BMW
Toyota

关联数组

方法一

1
2
3
4
5
6
<?php 
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>

/*输出结果:Peter is 35 years old.

方法二

1
2
3
4
5
6
7
8
<?php 
$age['peter']="35";
$age['ben']="37";
$age['joe']="43";
echo "Peter is " . $age['peter'] . " years old.";
?>

/*输出结果:Peter is 35 years old.

遍历关联数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php 
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");

foreach($age as $x=>$x_value)
{
echo "key=" . $x .",value=". $x_value;
echo "<br>";
}
?>

/*输出结果:
key=Peter,value=35
key=Ben,value=37
key=Joe,value=43



数组排序

sort() 升序排列

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php 
$cars=array("Volvo","BWM","Toyota");
sort($cars);
print_r($cars);
?>


/*输出结果:
Array
(
[0] => BWM
[1] => Toyota
[2] => Volvo
)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php 
$numbers=array(4,6,2,22,11);
sort($numbers);
print_r($numbers);
?>


/*输出结果:
Array
(
[0] => 2
[1] => 4
[2] => 6
[3] => 11
[4] => 22
)

rsort() 降序排列

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php 
$cars=array("Volvo","BWM","Toyota");
rsort($cars);
print_r($cars);
?>


/*输出结果:
Array
(
[0] => Volvo
[1] => Toyota
[2] => BWM
)

asort() 根据数组的值进行升序排列

1
2
3
4
5
<?php 
$age=array("peter"=>"35","ben"=>"37","joe"=>"43");
asort($age);
print_r($age);
?>

ksort() 根据数组的键进行升序排列

1
2
3
4
5
<?php 
$age=array("peter"=>"35","ben"=>"37","joe"=>"43");
ksort($age);
print_r($age);
?>