数组能够在单个变量中存储多个值1
2
3
4
$fruit=array("banana","apple","orange");
echo "I like ".$fruit[0]." ".$fruit[1]." ".$fruit[2];
PHP数组
在PHP中创建数组
在PHP中,array()函数用于创建数组
PHP数值数组
这里有两种创建数值数组的方法:
自动分配 ID 键(ID 键总是从 0 开始):$cars=array("Volvo","BMW","Toyota");
人工分配 ID 键:1
2
3$cars[0]="Volvo";
$cars[1]="BMW";
$cars[2]="Toyota";
1 |
|
获取数组的长度 -count()函数
count() 函数用于返回数组的长度(元素的数量)1
2
3
4
$fruit=array("banana","apple","orange");
echo count($fruit);
返回:3
遍历数组数值
1 |
|
PHP关联数组
关联数组是使用您分配给数组的指定的键的数组。
这里有两种创建关联数组的方法:1
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
or1
2
3$age['Peter']="35";
$age['Ben']="37";
$age['Joe']="43";
1 |
|
或者1
2
3
4
5
6
$age['Peter']='35';
$age['John']='65';
$age['Jim']='24';
echo "Peter is " . $age['Peter'] . " years old.";
输出同上。
遍历关联数组
使用foreach循环1
2
3
4
5
6
7
8
9
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
foreach($age as $i=>$i_value)
{
echo "Key=" . $i . ", Value=" . $i_value;
echo "<br>";
}
多维数组
一个数组中的值可以是另一个数组,另一个数组的值也可以是一个数组。
创建一个二维数组1
2
3
4
5
6
7
8
9
10
11
12
13
14
$cars = array
(
array("Volvo",100,96),
array("BMW",60,59),
array("Toyota",110,100)
);
$arrlength = count($cars);
for($i=0;$i<$arrlength;$i++)
{
print_r($cars[$i]);
echo "<br>";
}
创建一个多维数组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
header('Content-Type: text/html; charset=utf-8');
$sites = array
(
"runoob"=>array
(
"菜鸟教程",
"http://www.runoob.com"
),
"google"=>array
(
"Google 搜索",
"http://www.google.com"
),
"taobao"=>array
(
"淘宝",
"http://www.taobao.com"
)
);
print("<pre>"); // 格式化输出数组
print_r($sites);
print("</pre>");
//试着显示上面数组中的某个值:
echo $sites['runoob'][0] . '地址为:' . $sites['runoob'][1];
PHP数组排序
下列 PHP 数组排序函数:1
2
3
4
5
6sort() - 对数组进行升序排列
rsort() - 对数组进行降序排列
asort() - 根据关联数组的值,对数组进行升序排列
ksort() - 根据关联数组的键,对数组进行升序排列
arsort() - 根据关联数组的值,对数组进行降序排列
krsort() - 根据关联数组的键,对数组进行降序排列
sort() -对数组进行升序排序
字符串数组中的元素按照字母升序排序1
2
3
4
5
6
7
8
9
10
11
12
13
14
$fruit=array("banana","apple","orange");
$arraylength = count($fruit);
for($i=0;$i<$arraylength;$i++)
{
echo "$fruit[$i]",' ';
}
echo "<br>";
sort($fruit);
for($i=0;$i<$arraylength;$i++)
{
echo "$fruit[$i]",' ';
}
数字数组中的元素按照数字升序排列1
2
3
4
5
6
7
8
9
10
11
12
13
14
$number=array(5,3,4,6,1,2);
$arraylength = count($number);
for($i=0;$i<$arraylength;$i++)
{
echo "$number[$i]",' ';
}
echo "<br>";
sort($number);
for($i=0;$i<$arraylength;$i++)
{
echo "$number[$i]",' ';
}
resort() -对数组进行降序排序
同上
asort() - 根据数组的值,对数组进行升序排列
1 |
|
arsort() - 根据数组的值,对数组进行降序排列
同上
ksort() - 根据数组的值,对数组进行升序排列
1 |
|
krsort() - 根据数组的值,对数组进行降序排列
同上