一、概述
php 没有java的 map 和 list,也没有set。 看到的都是数组。初学php 记录下 php的数组,多维的先忽略
二、数组
1、索引数组,和java c 语言数组一样,用[0], [1] 数字下标访问
2、关联数组,类比java 的map,用key访问,key是个字符串。
三、数组初始化
1、索引数组
$contents = Array("a0","a1", "a2");
var_dump($contents);
输出
array(3) {
[0]=>
string(2) "a0"
[1]=>
string(2) "a1"
[2]=>
string(2) "a2"
}
2、关联数组
$contents = Array("a" => "a0", "b" => "a1");
$contents["c"]="a2";
var_dump($contents);
输出
array(3) {
["a"]=>
string(2) "a0"
["b"]=>
string(2) "a1"
["c"]=>
string(2) "a2"
}
3、还可以交错的使用
$contents = Array("a" => "a0", "b" => "a1");
$contents[0]="a2";
var_dump($contents);
$contents = Array("a0","a1", "a2");
$contents["nice"]="nice";
var_dump($contents);
输出
array(3) {
["a"]=>
string(2) "a0"
["b"]=>
string(2) "a1"
[0]=>
string(2) "a2"
}
array(4) {
[0]=>
string(2) "a0"
[1]=>
string(2) "a1"
[2]=>
string(2) "a2"
["nice"]=>
string(4) "nice"
}
三、数组轮询2种
$contents = Array(
"k1" => "a0",
"k2" => "a1",
"k3" => "a2");
//轮询值
foreach ($contents as $value) {
echo $value . "\n";
}
echo "------------\n";
//轮询内容
foreach ($contents as $key => $value) {
echo "key=$key, value=$value " . "\n";
}
输出:
a0
a1
a2
------------
key=k1, value=a0
key=k2, value=a1
key=k3, value=a2