Press confirm!
The reason why I implemented this function is to be able to measure the level of php development to a certain extent, which requires some skill. for the difficulties, I used two key-value arrays to cope with the required operations, which is also very convenient to the cache systems such as memcache.
The function is to fold and open a category to display the category of a product or other information. each item of this category can be folded or collapsed (expanded or shrunk if there is a subcategory ). the classification level is not fixed.
Raw data is an array
$ Cats = array (
Array (
'Id' => 1,
'Name' => 'video game ',
'Children '=> array (
Array (
'Id' => 3,
'Name' => 'competitive game 1 ',
'Children '=> null,
),
Array (
'Id' => 5,
'Name' => 'competitive games 2 ',
'Children '=> null,
),
Array (
'Id' => 7,
'Name' => 'competitive game 3 ',
'Children '=> null,
),
),
),
Array (
'Id' => 2,
'Name' => 'academic and educational ',
'Children '=> array (
Array (
'Id' => 4,
'Name' => 'natural science ',
'Children '=> null,
),
Array (
'Id' => 6,
'Name' => 'humanities and Social Sciences ',
'Children '=> null,
),
Array (
'Id' => 8,
'Name' => 'journal conferencing ',
'Children '=> null,
),
Array (
'Id' => 9,
'Name' => 'University name ',
'Children '=> array (
Array (
'Id' => 14,
'Name' => 'University of China ',
'Children '=> null,
),
Array (
'Id' => 16,
'Name' => 'International ',
'Children '=> null,
),
),
),
),
),
Array (
'Id' => 10,
'Name' => 'LIFE ',
'Children '=> array (
Array (
'Id' => 12,
'Name' => 'life 1 ',
'Children '=> null,
),
),
),
);
My corresponding processing
Function setLoopIndex ($ val, $ pref, & $ index, & $ nameArr ){
If (! Empty ($ val) {// not empty
Foreach ($ val as $ key => $ v ){
$ Child_pref = trim ($ pref. ''. $ key );
$ Index [$ v ['id'] = $ child_pref;
$ NameArr [$ child_pref] = $ v ['name']. ":". $ v ['id'];
SetLoopIndex ($ v ['children '], $ child_pref, & $ index, & $ nameArr); // cyclically process this subclass
}
}
}
// If the data volume is too large, put it in memcache or other methods, because they are all key value data storage methods.
$ Index = array (); // store the id and the corresponding index value
$ NameArr = array (); // store the index value and corresponding name
SetLoopIndex ($ cats, '', & $ index, & $ nameArr); // loop Processing
For the code, see the attachment. If you have any questions, please reply. Please click it! Place the extracted file in the root directory of the website. The accessed address is 127.0.0.1/test. php, you will know the other code. It is not very complicated. Continue to declare: you are welcome to shoot bricks, especially for better implementation!
This article from the "pure technology pure discussion" blog, please be sure to keep this source http://hjun169.blog.51cto.com/3600246/891533