Last active
May 28, 2020 08:17
-
-
Save Hootrix/7cea2787078a27f590e592c67f978257 to your computer and use it in GitHub Desktop.
0528面试上机题 无限子菜单实现
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Created by PhpStorm. | |
* User: yhtc | |
* Date: 2020/5/28 | |
* Time: 9:45 | |
*/ | |
//phpinfo(); | |
/** | |
* 面试上机题 | |
* 无限子菜单提交,html显示 | |
* table DDL | |
* | |
* CREATE TABLE `menu` ( | |
* `id` int(11) NOT NULL AUTO_INCREMENT, | |
* `name` varchar(45) DEFAULT NULL, | |
* `pid` varchar(45) DEFAULT NULL, | |
* PRIMARY KEY (`id`) | |
* ) ENGINE=InnoDB AUTO_INCREMENT=24 DEFAULT CHARSET=utf8mb4 | |
* | |
* 实际给我两个半小时没有写出来 很尴尬。下午冷静下来,吃完饭用了2个小时来解决这个问题。记录下 | |
* | |
* 无限子菜单的实现不难,我很少写过这种原生态代码(html+mysql基本操作语句)实际测试编写过程中的确很难,再加上已经有段时间没写PHP了。好吧,我的实现速度太慢了 被刷掉了。 THE END。 | |
*/ | |
$host = '127.0.0.1'; | |
$db = 'demo'; | |
$user = 'root'; | |
$pwd = 'root'; | |
//target="_blank" | |
header('Content-Type: text/html;charset=utf-8'); | |
$html = ' | |
<html><head> | |
<meta charset=\'UTF-8\'></head><form name="demo" method="post" action="" > | |
<select name="demo_select">'; | |
$con = mysqli_connect($host, $user, $pwd, $db); | |
$find = 'select * from demo.menu order by id,pid asc;'; | |
$query = mysqli_query($con, $find); | |
$list = []; | |
while ($r = mysqli_fetch_array($query)) { | |
$list[$r['id']] = $r; | |
} | |
// 循环处理 非递归 | |
$tree = []; | |
foreach ($list as $k => $v) { | |
if ($v['pid'] == 0) { | |
$tree[$v['id']] = &$list[$k]; # 引用传递挂载数据 | |
} else {# 当前为子节点 | |
$list[$v['pid']]['child'] [] = &$list[$k]; | |
} | |
} | |
unset($list); | |
# html 输出 | |
function tree_html($tree, $level) | |
{ | |
$res = ''; | |
foreach ($tree as $data) { | |
$level_str = str_repeat('--', $level); | |
$res .= "\n<option name=\"select_name_id\" value='${data['id']}'>${level_str}${data['name']} </option>"; | |
if (isset($data['child']) && !empty($data['child'])) { | |
$res .= tree_html($data['child'], $level + 1); | |
} | |
} | |
return $res; | |
} | |
$html .= tree_html($tree, 1); | |
$html .= '</select><input name="select_name_input" /><button name="submit">提交</button></form></html>'; | |
// 提交 | |
if (isset($_POST['select_name_input']) && !empty($_POST['select_name_input'])) { | |
$value = $_POST['select_name_input']; | |
$pid = $_POST['demo_select']; | |
$sql = "insert into menu (name,pid) values(\"$value\",$pid)"; | |
$rel = mysqli_query($con, $sql); | |
if (mysqli_insert_id($con)) { | |
echo '<script>alert("success");location.href = location.href</script>'; | |
} | |
} | |
$con->close(); | |
echo($html); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment