destoon省、市、区/县、乡/镇四级联动菜单前台效果
destoon省、市、区/县、乡/镇四级联动菜单后台
三,destoon省、市、区/县、乡/镇四级联动菜单(部分代码)
1)根节点入栈
foreach ($items as $id => $item) { if ($item['parentid'] == 0) { $stack[] = $id; $depths[$id] = 0; $arrparentids[$id] = '0'; } }
2)使用栈进行深度优先遍历
while (!empty($stack)) { $pid = array_pop($stack); if (!empty($children[$pid])) { foreach ($children[$pid] as $child_id) { $depths[$child_id] = $depths[$pid] + 1; $arrparentids[$child_id] = $arrparentids[$pid] . ',' . $pid; $stack[] = $child_id; } } }
3)按深度降序排序(从叶子节点到根节点)
arsort($depths);
4)从叶子节点开始向上计算
foreach ($depths as $id => $depth) { $parentid = $items[$id]['parentid']; if ($parentid && isset($arrchildids[$parentid])) { $arrchildids[$parentid] .= ',' . $arrchildids[$id]; } }
5)开启事务提高性能
DB::query("START TRANSACTION"); foreach ($items as $id => $item) { $child = isset($children[$id]) && !empty($children[$id]) ? 1 : 0; $arrparentid = isset($arrparentids[$id]) ? $arrparentids[$id] : '0'; $arrchildid = $arrchildids[$id]; // 修复:使用 addslashes 替代 DB::escape $sql = "UPDATE {$this->table} SET arrparentid = '".addslashes($arrparentid)."', arrchildid = '".addslashes($arrchildid)."', child = '".intval($child)."' WHERE areaid = '".intval($id)."'"; DB::query($sql); $counter++; // 每处理$batch_size条提交一次 if ($counter % $batch_size === 0) { DB::query("COMMIT"); DB::query("START TRANSACTION"); // 输出进度信息 if ($action == 'cache') { $progress = round($counter / $total * 100); echo "处理进度: {$progress}% ({$counter}/{$total})<br>"; flush(); } } }