php 代碼優(yōu)化之經典示例
經過上面的指導,發(fā)現(xià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)在有如上所示的結果
要求:要對這個已經按key進行排序了的數組進行操作,相同key的項進行處理。
提示:這個是很典型的母子表的結構,也就是說其實它是兩張表的合并,可以這樣處理成兩個數組,方便數組里面對塊的操作
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 |
實現(xiàn)如上數組分離代碼
這樣后,訪問tempArray的塊數據就非常方便了
foreach($tempArray as $row){
array1[$row['ID']] = $row['Key'];
array2[$row['Key']][] = $row;
}
訪問和處理代碼
foreach($array1 as $ID => $Key){
$this->doSomeThing($ID);
//訪問tempArray的塊數組$array2[$Key]
$this->doSomeThing2($array2[$Key]);
}
相關文章
php class中public,private,protected的區(qū)別以及實例分析
本篇文章是對php class中public,private,protected的區(qū)別以及實例進行了詳細的分析介紹,需要的朋友參考下2013-06-06

