PHP的數(shù)組,說(shuō)白了,就是關(guān)聯(lián)數(shù)據(jù)每一條數(shù)組都是以[索引,值]的形式保存的。其中索引默認(rèn)是以0開(kāi)始的數(shù)字。在未指定索引時(shí),PHP會(huì)從0開(kāi)始自動(dòng)生成索引。當(dāng)指定一個(gè)索引,PHP會(huì)從你指定索引最大正整數(shù)的下一個(gè)整數(shù)開(kāi)始。如果你指定的是小數(shù),PHP會(huì)取整數(shù)部分做為索引。
另外說(shuō)說(shuō)數(shù)組其它一些小東西:
array()可以聲明一個(gè)空數(shù)組;
array[] = $value 在數(shù)組存在時(shí),追加一個(gè)數(shù)據(jù);在數(shù)組不存時(shí),生成一個(gè)數(shù)組,并追加數(shù)據(jù)。
array[$index] = $value 在數(shù)組存在時(shí),追加或修改一個(gè)數(shù)據(jù);在數(shù)組不存時(shí),生成一個(gè)數(shù)組,并追加數(shù)據(jù)。
看下面的代碼:
復(fù)制代碼代碼如下:
// 聲明數(shù)組
$test01 = array();
// 追加數(shù)據(jù)
$test01[] = "a"; // array(0 => "a");
// 追加一個(gè)索引為"a",數(shù)據(jù)為"b"的數(shù)據(jù)
$test01["a"] = "b"; // array(0 => "a", "a" => "b");
// 修改索引為0的數(shù)據(jù)
$test01[0] = "c"; // array(0 => "c", "a" => "b");
// 另一種聲明方法
$test02 = array("a", "b", "c"); // array(0 => "a", 1 => "b", 2 => "c");
// 雖然聲明了一個(gè)字符串索引的數(shù)據(jù),但默認(rèn)索引還是從0開(kāi)始
$test03 = array("a" => "a", "b", "c"); // array("a" => "a", 0 => "b", 1 => "c");
// 聲明中最大的索引為2,雖然最近是索引是0,但默認(rèn)索引還是從3開(kāi)始
$test04 = array(2 => "a", 0=>"b", "c"); // array(2 => "a", 0 => "b", 3 => "c");
// 聲明一個(gè)小數(shù)索引會(huì)取其整數(shù)部分;指定索引時(shí),會(huì)修改之前聲明的值
$test05 = array("a", 2.7=>"b", 0=>"c"); // array(0 => "c", 2 => "b");
// 雖然聲明了負(fù)數(shù)索引,但默認(rèn)索引還是從0開(kāi)始
$test06 = array(-2 =>"a", "b", "c"); // array(-2 => "a", 1 => "b", 2 => "c");
// 多維數(shù)組的定義
$test07 = array($test01, $test02, $test03);
然后介紹數(shù)組的一些填充函數(shù),這些大多可以從手冊(cè)上查到,所以只作簡(jiǎn)單的介紹。
range($n, $m); 指定值的范圍。如range(2,4)生成數(shù)組 array(2,3,4)。
count($array); 取得數(shù)組的大小。
array_pad($array, $length, $value); 返回一個(gè)長(zhǎng)度$length的數(shù)組,原不足數(shù)組補(bǔ)值為$value,長(zhǎng)度足夠返回原數(shù)組。