A classic example of PHP code optimization
- 2020-03-31 21:39:33
- OfStack
After the above guidance, found really simple, now share with you.
ID
FIELD1
FIELD2 FIELD3 FIELD4 The Key
1
* * * * * * * * * * * * meat1
2
* * * * * * * * * * * * meat1 3
* * * * * * * * * * * * meat1 4 * * * * * * * * * * * * meat1 5
* * * * * * * * * * * * fruit2 6 * * * * * * * * * * * * fruit2 7
* * * * * * * * * * * * fruit2 8
* * * * * * * * * * * * fruit2 9
* * * * * * * * * * * * fruit2 10
* * * * * * * * * * * * food3 11
* * * * * * * * * * * * food3
Now the result is as shown above
Requirements: to operate on the array sorted by key, and to process items with the same key.
Tip: this is a typical parent-child table structure, which means that it is actually a merge of two tables, which can be processed into two arrays to facilitate block-facing operations in the array
Array1: ID | Key
The 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 The 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
Implementation of the above array separation code
This makes it easy to access tempArray's block data
{foreach ($tempArray as $row)
Array1 [$row [' ID ']] = $row [' Key '];
Array2 [$row [' Key ']], [] = $row;
}
Access and process code
The foreach ($array1 as $ID = > {$Key)
$this - > DoSomeThing ($ID);
// access to block array of tempArray $array2[$Key]
$this - > DoSomeThing2 ($array2 ($Key));
}