無(wú)限級(jí)分類(lèi)子分類(lèi)讀取
問(wèn)題:
如何使用 thinkphp 框架讀取無(wú)限級(jí)分類(lèi)中的所有子分類(lèi),并以多維數(shù)組形式返回?
解決方案:
立即學(xué)習(xí)“PHP免費(fèi)學(xué)習(xí)筆記(深入)”;
首先,要解決這個(gè)問(wèn)題,我們需要?jiǎng)?chuàng)建一個(gè)函數(shù) getchildarea 來(lái)讀取子分類(lèi),該函數(shù)將以給定的地區(qū) id 作為參數(shù),并以遞歸方式遍歷所有子分類(lèi)。
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) { $res[] = $val; getchildarea($val['id']); } } return $res; }
然而,這個(gè)函數(shù)返回的是一維數(shù)組。要獲得多維數(shù)組,我們需要將一維數(shù)組轉(zhuǎn)換為多維數(shù)組。我們可以使用 deal_list_to_tree2 函數(shù)來(lái)實(shí)現(xiàn)此目的:
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; }
調(diào)用 deal_list_to_tree2 函數(shù)可以將一維數(shù)組轉(zhuǎn)換為多維數(shù)組:
$multidimensionalData = deal_list_to_tree2($result);
現(xiàn)在,你將擁有一個(gè)包含所有子分類(lèi)的多維數(shù)組。請(qǐng)注意,deal_list_to_tree2 函數(shù)是一個(gè)通用的函數(shù),它可以用于轉(zhuǎn)換任何一維數(shù)組到多維數(shù)組。
? 版權(quán)聲明
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載。
THE END