在php中 array() 函数用于创建数组。
例如:
$cars=array("Volvo","BMW","Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
输出结果是:I like Volvo, BMW and Toyota.
在phop中用count()函数来获取数组的元素的个数
$cars=array("Volvo","BMW","Toyota");
echo count($cars);
?>
输出结果是:3
知道数组的个数了我们就可以遍历数组了
$cars=array("Volvo","BMW","Toyota");
$catscount=count($cars);
for($i=0;$i<$catscount<$i++)
{
echo $cars[$i];
echo "";
}
?>
输出结果是:
Volvo
BMW
Toyota
此处数组的下标是从0开始的 但是还有一种数组的键值不是数字而是字符 这就是是所谓的关联数组
关联数组需遍历
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
foreach($age as $x=>$x_value) //$x 表示键值相当于一般数组的下标 $x_value表示键值所指向的值
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "
";
}
?>
数组的排序
sort() - 对数组进行升序排列
rsort() - 对数组进行降序排列
asort() - 根据关联数组的值,对数组进行升序排列
ksort() - 根据关联数组的键,对数组进行升序排列
arsort() - 根据关联数组的值,对数组进行降序排列
krsort() - 根据关联数组的键,对数组进行降序排列
例如:
$cars=array("Volvo","BMW","Toyota");
echo sort($cars);//升序排列
print_r($cars);
$numbers=array(4,6,2,22,11);
rsort($numbers);
print_r($numbers);
$age=array("Peter"=>"38","Ben"=>"37","Joe"=>"43");
asort($age);
print_r($age);
ksort($age);
print_r($age);
arsort($age);
print_r($age);
krsort($age);
print_r($age);
?>
输出结果
Array
(
[0] => BMW
[1] => Toyota
[2] => Volvo
)
Array
(
[0] => 22
[1] => 11
[2] => 6
[3] => 4
[4] => 2
)
Array
(
[Ben] => 37
[Peter] => 38
[Joe] => 43
)
Array
(
[Ben] => 37
[Joe] => 43
[Peter] => 38
)
Array
(
[Joe] => 43
[Peter] => 38
[Ben] => 37
)
Array
(
[Peter] => 38
[Joe] => 43
[Ben] => 37
)
多维数组
例如:
$sites = array
(
"runoob"=>array
(
"菜鸟教程",
"http://www.runoob.com"
),
"google"=>array
(
"Google 搜索",
"http://www.google.com"
),
"taobao"=>array
(
"淘宝",
"http://www.taobao.com"
)
);
print(""
); // 格式化输出数组
print_r($sites);
print("
");
?>
// 二维数组:
$cars = array
(
array("Volvo",100,96),
array("BMW",60,59),
array("Toyota",110,100)
);
?>