作為一名C++程序員,在轉做PHP開發的過程中,對PHP數組產生了一些混淆,與C++數組有相似的地方,也有一些不同,下面就全面地分析一下PHP的數組及其與C++中相應數據類型的區別和聯系。
1、數值數組:也叫索引數組,即以數字(從0 開始)作為數組下標。相當於C++中的vector。
2、關聯數組:以字符串作為數組下標。相當於C++中的map。
3、多維數組:數組中每個元素也是一個數組。其子數組中的每個元素也可以是數組。
1、數值數組
a、如下例子中,會自動分配數字ID鍵。 $names = array("Peter","Joe","Lily"); b、如下例子中,我們人工分配數字ID鍵。 $names[0] = "Peter"; $names[1] = "Joe"; $names[2] = "Lily"; 可以在腳本中使用這些ID鍵: <?php $names[0] = "Peter"; $names[1] = "Joe"; $names[2] = "Lily"; echo $names[0]." and ".$names[1]." are ".$names[2]."'s neighbors"; /* 何問起 hovertree.com */ ?>
2、關聯數組:
例子1 $ages = array("Peter"=>32, "Joe"=>30, "Lily"=>28); 例子2 本例與例子1相同,只是另一種創建數組的方法。 $ages["Peter"] = "32"; $ages["Joe"] = "30"; $ages["Lily"] = "28"; 在腳本中使用關聯數組: <?php $ages["Peter"] = "32"; $ages["Joe"] = "30"; $ages["Lily"] = "28"; echo "Peter is ".$ages["Peter"]." years old."; /* 何問起 hovertree.com */ ?> 以上腳本輸出: Peter is 32 years old.
3、多維數組:
在本例中,我們創建了一個帶有自動分配數字ID鍵的多維數組: $families = array { "Griffin"=>array { "Peter", "Lois", "Megan" }, "Quagmire"=>array { "Glenn" }, "Brown"=>array { "Cleveland", "Loretta", "Junior" } }; echo "Is " . $families['Griffin'][2] . " a part of the Griffin family?"; 以上代碼輸出: Is Megan a part of the Griffin family?
1、for循環遍歷 for循環只能遍歷索引數組。 <?php $names = array("Peter","Joe","Lily"); for($id=0;$id<count($names);++$id) { echo $names[$id]; } ?> 2、foreach遍歷 即可以遍歷索引數組,也可以遍歷關聯數組 遍歷索引數組 foreach(array_expression as $value) { 循環體; } 遍歷關聯數組 foreach(array_expression as $key=>$value) { 循環體; } A、一維數組遍歷 索引數組 <?php $contact = array("李某","xx公司","[email protected]"); foreach($contact as $value) { echo $value; } ?> <?php $contact = array("姓名"=>"李某","公司"=>"xx公司","郵箱"=>"[email protected]"); foreach($contact as $key=>$value) { echo $key.":".$value; } ?> B、多維數組遍歷 <?php $wage = array( "市場部"=array( array(1,"李某","市場經理",8000), array(2,"王某","市場專員",5000), array(3,"劉某","市場專員",7000) ), "產品部"=array( array(1,"李某","產品經理",9000), array(2,"王某","產品專員",6000), array(3,"劉某","產品專員",5000) ), "賬務部"=array( array(1,"李某","賬務經理",7000), array(2,"王某","賬務專員",6000), array(3,"劉某","賬務專員",5000) ) ); foreach($wage as $section=>$table) { echo $section."部門人員如下"; foreach($table as $row) { foreach($row as $value) { echo $value; } } } /* 何問起 hovertree.com */ ?>
推薦:http://www.cnblogs.com/roucheng/p/phpdongtai.html