$sql_host = 'mysql-server-5.6';
$sql_user = 'admin';
$sql_pwd = '123456';
$sql_db = 'jtbc';
$conn = mysqli_connect($sql_host, $sql_user, $sql_pwd, $sql_db, 3306) or die("数据库链接失败");
mysqli_real_query($conn, "SET NAMES 'utf8'");
mysqli_select_db($conn, $sql_db) or die("没有" . $sql_db . "这个数据库,或是被管理员断开了链接,请稍后再试");
function _query($sql, $data = [], $isone = false)
{
global $conn;
$keys = [];
$values = [];
if (!empty($data) && !is_array($data)) {
$isone = $data;
} elseif (is_array($data)) {
foreach ($data as $k => $v) {
$keys[] = ":$k";
$values[] = '"' . addslashes($v) . '"';
}
}
$sql = trim(str_replace($keys, $values, $sql));
$res = mysqli_query($conn, $sql);
if (is_bool($res)) {
return $res;
}
switch (true) {
case preg_match( "/^INSERT\s/i", $sql ):
return @mysqli_insert_id($conn);
break;
case preg_match( "/^UPDATE\s/i", $sql ):
case preg_match( "/^DELETE\s/i", $sql ):
return $res;
break;
default:
if (mysqli_num_rows($res) == 1 && $isone) {
return mysqli_fetch_array($res, MYSQLI_ASSOC);
} else {
$arr = array();
while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
$arr[] = $row;
}
return $arr;
}
break;
}
}
function getChild($key = '', $level = 1, $array = []){
if (empty($array)) {
$sql = 'select key_name,pid_name from test_6';
$array = _query($sql);
}
if (is_string($key)) $key = explode(',', $key);
for ($i = 1;$i<= $level;++$i) {
$keys = [];
foreach ($array as $k => $v) {
if (in_array($v['key_name'], $key)) {
$keys[] = $v['pid_name'];
}
}
$key = $keys;
}
return $key;
}
print_r(getChild('A',2));
INSERT INTO `test_6` (`id`, `pid_name`, `key_name`) VALUES (1, 'A', ' ');
INSERT INTO `test_6` (`id`, `pid_name`, `key_name`) VALUES (2, 'B', ' ');
INSERT INTO `test_6` (`id`, `pid_name`, `key_name`) VALUES (3, 'C', ' ');
INSERT INTO `test_6` (`id`, `pid_name`, `key_name`) VALUES (4, 'A_1', 'A');
INSERT INTO `test_6` (`id`, `pid_name`, `key_name`) VALUES (5, 'A_2', 'A');
INSERT INTO `test_6` (`id`, `pid_name`, `key_name`) VALUES (6, 'A_1_1', 'A_1');
INSERT INTO `test_6` (`id`, `pid_name`, `key_name`) VALUES (7, 'A_1_2', 'A_1');
INSERT INTO `test_6` (`id`, `pid_name`, `key_name`) VALUES (8, 'A_1_3', 'A_1');
INSERT INTO `test_6` (`id`, `pid_name`, `key_name`) VALUES (9, 'A_2_1', 'A_2');
INSERT INTO `test_6` (`id`, `pid_name`, `key_name`) VALUES (10, 'A_2_2', 'A_2');
INSERT INTO `test_6` (`id`, `pid_name`, `key_name`) VALUES (11, 'A_1_2_1', 'A_1_2');
INSERT INTO `test_6` (`id`, `pid_name`, `key_name`) VALUES (12, 'A_1_2_2', 'A_1_2');
INSERT INTO `test_6` (`id`, `pid_name`, `key_name`) VALUES (13, 'A_1_3_1', 'A_1_3');
INSERT INTO `test_6` (`id`, `pid_name`, `key_name`) VALUES (14, 'A_1_3_2', 'A_1_3');