Today I encountered such a problem. The processed array $ tempArray is in the following format (the key has been sorted ), next, we need to process the chunks based on this result. the method I use is to differentiate the chunks by key, assign the chunks to other variables, and then perform some operations, in this way, a lot of for and foreach are used, and the amount of code is large, so they are returned.
After the guidance above, I found it really easy to share with you.
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 |
The result is as shown above.
Requirement: to operate on the array that has been sorted by key, the items with the same key are processed.
Tip: This is a typical parent-child table structure. that is to say, it is actually a combination of two tables. it can be processed into two arrays to facilitate block operations in the array.
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 |
Implement the preceding array separation code
In this way, it is very convenient to access the block data of tempArray.
Foreach ($ tempArray as $ row ){
Array1 [$ row ['id'] = $ row ['key'];
Array2 [$ row ['key'] [] = $ row;
}
Access and process code
Foreach ($ array1 as $ ID => $ Key ){
$ This-> doSomeThing ($ ID );
// Access the block array of tempArray $ array2 [$ Key]
$ This-> doSomeThing2 ($ array2 [$ Key]);
}