This article mainly introduces how thinkphp achieves unlimited Classification when recursion is used. Interested friends can refer to the examples in this article to share with you the detailed code of thinkphp to implement unlimited classification, I hope to inspire you to learn about unlimited classification.
Database: test
Data Table :( tp_category ):
Common/conf/config. php
'Db _ config2' => array ('db _ type' => 'mysql', 'db _ user' => 'root ', 'db _ pwd' => '', 'db _ host' => 'localhost', 'db _ port' => '123 ', 'db _ name' => 'test', 'db _ prefix' => 'tp _ ', // database table PREFIX 'db _ charset' => 'utf8 ', // Character Set 'db _ debug' => TRUE, // After the database DEBUG mode is enabled, you can record the SQL log 3.2.3 added ),
Common/function. php traversal function loop
/** Recursive traversal * @ param $ data array * @ param $ id int * return array **/function recursion ($ data, $ id = 0) {$ list = array (); foreach ($ data as $ v) {if ($ v ['pid '] = $ id) {$ v ['son'] = recursion ($ data, $ v ['id']); if (empty ($ v ['son']) {unset ($ v ['son']);} array_push ($ list, $ v) ;}} return $ list ;}
Controller/IndexController. class. php
public function test() { $category = M('category', '', C('DB_CONFIG2'))->select(); $result = loop($category); var_dump($result); $this->assign('list', $result); $this->display();}
Output in the template (View/Index/test.html) (only two levels of classification are supported. If you want to display all types, we recommend that you convert the array to JSON format and then generate it using AJAX requests)
Subsequent (ajax requests show all types recursively ):
Method Controller/IndexController. class. php
Public function test () {$ this-> display ();} public function resultCategory () {$ category = M ('category ','', C ('db _ CONFIG2 ')-> select (); $ result = loop ($ category); $ this-> ajaxReturn (array ('data' => $ result, 'status' => '1', 'info' => 'list retrieved successfully '));}
Template View/Index/test.html
Classification test