changliang.io

PHP学习笔记之一:数组

字数统计: 189阅读时长: 1 min
2020/08/17 Share

创建一个一位数组,使用foreach遍历数组:

1
2
3
4
5
6
<?php
$arr = array("one", "two", "three");
foreach ($arr as $value) {
echo "Value: $value<br />\n";
}
?>

创建一个二维数组,使用foreach遍历数组:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php
$fruits = array (
"fruits" => array("a" => "orange", "b" => "banana", "c" => "apple"),
"numbers" => array(1, 2, 3, 4, 5, 6),
"holes" => array("first", 5 => "second", "third")
);
$fruits[0]["d"]="orange"; //无法找到标识为“0”的数组,故此时d => orange的值会追加到$fruits数组最后一行
$fruits["fruits"]["d"]="Mango"; //此时可以正常将d => Mango的值会追加到$fruits数组最后
$fruits["fruits"]["c"]="Mango"; //此时会覆盖$fruits数组索引为"c"的原值"apple"

foreach ($fruits as $k=>$i) {
foreach ($i as $a=>$b) {
echo "$a.$b<br />\n";
}

}
?>
目录