在thinkphp框架中,我們可以通過遞歸的方式讀取無限級分類的子分類。使用getchildarea()函數時,返回的是一維數組,如果您需要多維數組,可以采用以下方式改進:
function getchildarea($id){ if(!$id){ return; } static $area; $area = $area ?? new appcommonmodelarea; $result = collection($area->where(['pid' => $id])->order('id desc')->select())->toarray(); static $res = []; if($result){ foreach ($result as $key => $val) { $val['children'] = getchildarea($val['id']); $res[] = $val; } } return $res; }
配合deal_list_to_tree2()方法,可以將一維數組轉化為多維數組:
<?php /** * 方法 deal_list_to_tree2,一維數組根據$parent_id的值轉為多維數組 * * @param array $data 待處理的一維數組 * @param string $pkname 用于轉化為多維數組的主鍵字段 * @param string $pidname 用于轉化為多維數組的字段(根據該字段值轉換) * @param string $childname 子級的字段名 * @param bool $is_empty_childrens 是否返回空的子數組(childrens[])(true:是,false:否) * @param string $rootid 根節點$pkname值 * * @return array $new_data 返回處理好的(多層級)多維數組 * */ function deal_list_to_tree2($data, $pkname='id', $pidname='parent_id', $childname='children_list', $is_empty_childrens=false, $rootid=''){ $new_data = []; if(!empty($data)){ foreach($data as $sordata){ if(array_key_exists($childname, $sordata) && !empty($sordata[$childname])){ $res = deal_list_to_tree2($data, $pkname, $pidname, $childname, $is_empty_childrens, $sordata[$pkname]); }else{ if($sordata[$pidname] == $rootid){ if($sordata[$pkname] != $rootid){ $res = deal_list_to_tree2($data, $pkname, $pidname, $childname, $is_empty_childrens, $sordata[$pkname]); } if(!empty($res) && !$is_empty_childrens){ if(array_key_exists($childname, $sordata)) { if(array_key_exists($childname, $sordata)){ for($i=0; $i < count($res); $i++){ $sordata[$childname][] = $res[$i]; } }else{ $sordata[$childname][] = $res; } }else{ $sordata[$childname] = $res; } } $new_data[] = $sordata; } } } } return $new_data; }
這樣,返回的多維數組格式為:
[ { "id": 1, "area_name": "安徽省", "pid": 0, "level": 1, "children": [ { "id": 4, "area_name": "合肥市", "pid": 1, "level": 2, "children": [ { "id": 7, "area_name": "肥東縣", "pid": 4, "level": 3, "children": [ { "id": 8, "area_name": "桃園鎮", "pid": 7, "level": 4, "children": [ { "id": 9, "area_name": "八斗鄉", "pid": 8, "level": 5 } ] }, { "id": 10, "area_name": "長豐縣", "pid": 4, "level": 3 } ] } ] } ] }, { "id": 2, "area_name": "江蘇省", "pid": 0, "level": 1 }, { "id": 3, "area_name": "江西省", "pid": 0, "level": 1, "children": [ { "id": 5, "area_name": "南昌市", "pid": 3, "level": 2 }, { "id": 6, "area_name": "九江市", "pid": 3, "level": 2 } ] } ]
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END