php 代碼優(yōu)化之經(jīng)典示例
經(jīng)過上面的指導(dǎo),發(fā)現(xiàn)真的好簡(jiǎn)單,現(xiàn)在與大家一同分享。
| ID |
FIELD1 |
FIELD2 | FIELD3 | FIELD4 | Key |
| 1 |
*** | *** | *** | *** | meat1 |
| 2 |
*** | *** | *** | *** | meat1 |
| 3 |
*** | *** | *** | *** | meat1 |
| 4 | *** | *** | *** | *** | meat1 |
| 5 |
*** | *** | *** | *** | fruit2 |
| 6 | *** | *** | *** | *** | fruit2 |
| 7 |
*** | *** | *** | *** | fruit2 |
| 8 |
*** | *** | *** | *** | fruit2 |
| 9 |
*** | *** | *** | *** | fruit2 |
| 10 |
*** | *** | *** | *** | food3 |
| 11 |
*** | *** | *** | *** | food3 |
現(xiàn)在有如上所示的結(jié)果
要求:要對(duì)這個(gè)已經(jīng)按key進(jìn)行排序了的數(shù)組進(jìn)行操作,相同key的項(xiàng)進(jìn)行處理。
提示:這個(gè)是很典型的母子表的結(jié)構(gòu),也就是說其實(shí)它是兩張表的合并,可以這樣處理成兩個(gè)數(shù)組,方便數(shù)組里面對(duì)塊的操作
array1:ID|Key
| ID |
Key |
| 1 |
meat1 |
| 2 |
meat1 |
| 3 |
meat1 |
| 4 | meat1 |
| 5 |
fruit2 |
| 6 | fruit2 |
| 7 |
fruit2 |
| 8 |
fruit2 |
| 9 |
fruit2 |
| 10 |
food3 |
| 11 |
food3 |
array2:key => array(ID,FIELD1,FIELD2,FIELD3,FIELD4,FIELD5,Key)
| ID |
FIELD1 |
FIELD2 | FIELD3 | FIELD4 | Key | |
| meat1=> |
1 |
*** | *** | *** | *** | meat1 |
| 2 |
*** | *** | *** | *** | meat1 | |
| 3 |
*** | *** | *** | *** | meat1 | |
| 4 | *** | *** | *** | *** | meat1 | |
| fruit2=> | 5 |
*** | *** | *** | *** | fruit2 |
| 6 | *** | *** | *** | *** | fruit2 | |
| 7 |
*** | *** | *** | *** | fruit2 | |
| 8 |
*** | *** | *** | *** | fruit2 | |
| 9 |
*** | *** | *** | *** | fruit2 | |
| food3=> | 10 |
*** | *** | *** | *** | food3 |
| 11 |
*** | *** | *** | *** | food3 |
實(shí)現(xiàn)如上數(shù)組分離代碼
這樣后,訪問tempArray的塊數(shù)據(jù)就非常方便了
foreach($tempArray as $row){
array1[$row['ID']] = $row['Key'];
array2[$row['Key']][] = $row;
}
訪問和處理代碼
foreach($array1 as $ID => $Key){
$this->doSomeThing($ID);
//訪問tempArray的塊數(shù)組$array2[$Key]
$this->doSomeThing2($array2[$Key]);
}
相關(guān)文章
php class中public,private,protected的區(qū)別以及實(shí)例分析
本篇文章是對(duì)php class中public,private,protected的區(qū)別以及實(shí)例進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-06-06
php相對(duì)當(dāng)前文件include其它文件的方法
這篇文章主要介紹了php相對(duì)當(dāng)前文件include其它文件的方法,實(shí)例分析了php中include引入文件的使用技巧,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2015-03-03
使用php語(yǔ)句將數(shù)據(jù)庫(kù)*.sql文件導(dǎo)入數(shù)據(jù)庫(kù)
這篇文章主要介紹了如何使用php語(yǔ)句將數(shù)據(jù)庫(kù)*.sql文件導(dǎo)入數(shù)據(jù)庫(kù),需要的朋友可以參考下2014-05-05
PHP內(nèi)置的Math函數(shù)效率測(cè)試
這篇文章主要介紹了PHP內(nèi)置的Math函數(shù)效率測(cè)試,以實(shí)例形式測(cè)試了相關(guān)的PHP內(nèi)置數(shù)學(xué)運(yùn)算函數(shù)的執(zhí)行時(shí)間,分析其運(yùn)行效率,需要的朋友可以參考下2014-12-12

