array( 'db_type' => 'mysql'.'db_user' => 'root'.'db_pwd' => ''.'db_host' => 'localhost'.'db_port' => '3306'.'db_name' => 'test'.'DB_PREFIX' => 'tp_'.// 數(shù)據(jù)庫表前綴 'DB_CHARSET'=> 'utf8'.// 字符集 'DB_DEBUG' => TRUE.// 數(shù)據(jù)庫調(diào)試模式 開啟后可以記錄SQL日志 3.2.3新增),。Common/function.php 遍歷函數(shù)loop。" />
數(shù)據(jù)庫:test
數(shù)據(jù)表:(tp_category):
Common/conf/config.php
'DB_CONFIG2' => array( 'db_type' => 'mysql', 'db_user' => 'root', 'db_pwd' => '', 'db_host' => 'localhost', 'db_port' => '3306', 'db_name' => 'test', 'DB_PREFIX' => 'tp_', // 數(shù)據(jù)庫表前綴 'DB_CHARSET'=> 'utf8', // 字符集 'DB_DEBUG' => TRUE, // 數(shù)據(jù)庫調(diào)試模式 開啟后可以記錄SQL日志 3.2.3新增 ),
Common/function.php 遍歷函數(shù)loop
/* * 遞歸遍歷 * @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(); }
在模板(View/Index/test.html)中輸出(僅支持2級分類,如果想全部顯示,建議先把數(shù)組轉(zhuǎn)換成JSON格式,然后通過AJAX請求,JS生成)
{$vo.category} {$cate.category}
后續(xù)(ajax請求,遞歸顯示所有分類):
方法 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'=>'獲取列表成功')); }
模板View/Index/test.html
分類測試
JS遞歸(特殊):
這個函數(shù)相當于實現(xiàn)php的str_repeat函數(shù)
/* 字符串重復(fù)函數(shù) */ if(!String.str_out_times) { String.prototype.str_out_times = function(l) { return new Array(l+1).join(this); } }
// 定位到當前選擇 function recursion(selector, data, j, pid) { var space = ' ┠ '; if(!data) return false; $.each(data, function(i, item) { var opt = $('');selector.append(opt); if(item.son && (item.son).length>0) { recursion(selector, item.son, ++j); j=0; } }); // 當前是哪個分類 selector.find('option').each(function() { if($(this).val() == pid) { $(this).attr('selected', 'selected'); } }); }
為什么j=0呢。因為執(zhí)行順序感覺與php不同,這里是從上到下加載。
ajax請求數(shù)據(jù):
$('.btn-edit').click(function() { var id = $(this).data('id'); $.post("{:U('Article/editArticle')}", {id: id}, function(res) { // 分類 $('[name="pid"]').html(''); recursion($('[name="pid"]'), res.sort, 0, res.pid); $('[name="id"]').val(res.id); $('[name="title"]').val(res.title); $('[name="summary"]').val(res.summary); $('#thumbnailImg').attr('src', "__UPLOAD__"+'/thumbnail/'+res.thumbnail); ue.setContent(res.content); $('#modal-edit').modal('show'); }); });
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com