無限級分類子分類讀取
問題:
如何使用 thinkphp 框架讀取無限級分類中的所有子分類,并以多維數組形式返回?
解決方案:
立即學習“PHP免費學習筆記(深入)”;
首先,要解決這個問題,我們需要創建一個函數 getchildarea 來讀取子分類,該函數將以給定的地區 id 作為參數,并以遞歸方式遍歷所有子分類。
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; }
然而,這個函數返回的是一維數組。要獲得多維數組,我們需要將一維數組轉換為多維數組。我們可以使用 deal_list_to_tree2 函數來實現此目的:
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; }
調用 deal_list_to_tree2 函數可以將一維數組轉換為多維數組:
$multidimensionalData = deal_list_to_tree2($result);
現在,你將擁有一個包含所有子分類的多維數組。請注意,deal_list_to_tree2 函數是一個通用的函數,它可以用于轉換任何一維數組到多維數組。
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END