數組的類型
索引數組
定義
- 方式一:
$animal = array("monkey","dog","cat");
- 方式二:
$animal[0] = "monkey";
$animal[1] = "dog";
$animal[2] = "cat";
獲取指定索引位置上的值:
echo "$animal[0],$animal[1],$animal[2]";
遍歷索引數組
<?php
$animal[0] = "monkey";
$animal[1] = "dog";
$animal[2] = "cat";
foreach ($animal as $a) {
echo $a . "</br>";
}
?>
索引數組的長度
通過count()函數可以計算數組的長度
echo count($animal);
關聯數組
定義
- 方式一:
$money = array("pen" => 20,"notes" => 5);
- 方式二:
$money["pen"] = 20;
$money["notes"] = 5;
獲取
echo $money["pen"];
遍歷關聯數組
<?php
$money["pen"] = 20;
$money["notes"] = 5;
foreach($money as $key => $value) {
echo "{$key}對應{$value}</br>";
}
?>
多維數組
定義
如下是定義一個三行三列的多維數組:
$multi = array
(
array(1,"pen",20),
array(2,"notes",5),
array(3,"eraser",2)
);
遍歷
需要使用for循環嵌套來實現多維數組的遍歷
<?php
$multi = array
(
array(1,"pen",20),
array(2,"notes",5),
array(3,"eraser",2)
);
for($row = 0;$row < 3; $row++) {
for($col = 0;$col < 3;$col++) {
echo "{$multi[$row][$col]} ";
}
echo "</br>";
}
?>
多維數組遍歷結果