這裡沒有用遞迴查詢,而是用得另一種處理方法
思路:獲取到資料庫的所有分類,通過**,根據pid,返回分類樹,
方法**如下:
/**
* 分類樹
*/public static function gettree($data)
//halt($items);
$tree = ;
foreach ($items as $id=>$item)else
}return $tree;
}
資料庫的資料為:
呼叫分類樹之前:(我在查詢返回後,就把id轉換為category_id了,下面得category_id就是資料庫對應得id)
^ array:11 [
0 => array:3 [
"category_id" => 11
"name" => "小公尺8"
"pid" => 2
] 1 => array:3 [
"category_id" => 10
"name" => "顯示器"
"pid" => 6
] 2 => array:3 [
"category_id" => 9
"name" => "主機板"
"pid" => 6
] 3 => array:3 [
"category_id" => 8
"name" => "聯想"
"pid" => 5
] 4 => array:3 [
"category_id" => 7
"name" => "戴爾"
"pid" => 5
] 5 => array:3 [
"category_id" => 6
"name" => "華碩"
"pid" => 5
] 6 => array:3 [
"category_id" => 5
"name" => "電腦"
"pid" => 0
] 7 => array:3 [
"category_id" => 4
"name" => "小公尺10"
"pid" => 2
] 8 => array:3 [
"category_id" => 3
"name" => "紅公尺"
"pid" => 2
] 9 => array:3 [
"category_id" => 2
"name" => "小公尺"
"pid" => 1
] 10 => array:3 [
"category_id" => 1
"name" => "手機"
"pid" => 0
]]
呼叫分類樹之後:
^ array:2 [
0 => array:4 [
"category_id" => 5
"name" => "電腦"
"pid" => 0
"list" => array:3 [
0 => array:3 [
"category_id" => 8
"name" => "聯想"
"pid" => 5
]1 => array:3 [
"category_id" => 7
"name" => "戴爾"
"pid" => 5
]2 => array:4 [
"category_id" => 6
"name" => "華碩"
"pid" => 5
"list" => array:2 [
0 => array:3 [
"category_id" => 10
"name" => "顯示器"
"pid" => 6
]1 => array:3 [
"category_id" => 9
"name" => "主機板"
"pid" => 6]]
]]] 1 => array:4 [
"category_id" => 1
"name" => "手機"
"pid" => 0
"list" => array:1 [
0 => array:4 [
"category_id" => 2
"name" => "小公尺"
"pid" => 1
"list" => array:3 [
0 => array:3 [
"category_id" => 11
"name" => "小公尺8"
"pid" => 2
]1 => array:3 [
"category_id" => 4
"name" => "小公尺10"
"pid" => 2
]2 => array:3 [
"category_id" => 3
"name" => "紅公尺"
"pid" => 2]]
]]]]
json格式展示效果:
這就完成了,根據pid分類的效果。
無限極分類
面試的時候被問到無限極分類的設計和實現,比較常見的做法是在建表的時候,增加乙個pid欄位用來區別自己所屬的分類 array array array id 1,pid 0,name 河北省 array id 2,pid 0,name 北京市 array id 3,pid 1,name 邯鄲市 arra...
php無限極分類處理
無限極分類處理 通過遞迴方式實現 param section 原始資料array param html 介面顯示字首,比如 param spear 分級中所需要使用的分隔符,支援html轉義 param fid 父級id,頂級為0 param level 層級關係 str repeat string...
PHP無限極分類樹
建表資料 create table limit tree id int 10 unsigned not null auto increment,pid int 10 unsigned not null default 0 name varchar 64 not null default primar...