以下是完整的 PHP 自动匹配诊断函数,它从 MySQL 数据库中的 diagnosis_rules 表 中读取规则并匹配用户输入的症状、舌象、脉象,输出最佳证型与推荐方剂。
✅ 一、准备工作(确保以下):
- 已建立
diagnosis_rules表 - 表中字段包括:
diagnosis,formula,symptoms,tongue,pulse(症状和脉象为 JSON 格式)
🧠 二、PHP 函数:diagnose_from_db()
<?php
function diagnose_from_db($conn, $user_symptoms, $tongue_input, $pulse_input) {
$sql = "SELECT * FROM diagnosis_rules";
$result = mysqli_query($conn, $sql);
$best_match = null;
$max_score = 0;
while ($row = mysqli_fetch_assoc($result)) {
$score = 0;
$rule_symptoms = json_decode($row['symptoms'], true);
$rule_pulse = json_decode($row['pulse'], true);
$rule_tongue = $row['tongue'];
// 症状匹配:关键词模糊匹配
foreach ($rule_symptoms as $keyword) {
foreach ($user_symptoms as $symptom) {
if (strpos($symptom, $keyword) !== false) {
$score++;
break;
}
}
}
// 舌象匹配
if (!empty($rule_tongue) && $rule_tongue === $tongue_input) {
$score++;
}
// 脉象匹配
foreach ($rule_pulse as $p_keyword) {
foreach ($pulse_input as $p_input) {
if (strpos($p_input, $p_keyword) !== false) {
$score++;
break;
}
}
}
// 记录最佳匹配
if ($score > $max_score) {
$max_score = $score;
$best_match = [
'diagnosis' => $row['diagnosis'],
'formula' => $row['formula'],
'score' => $score
];
}
}
return $best_match ?: ['diagnosis' => '无匹配证型', 'formula' => '请人工判断', 'score' => 0];
}
?>
🧪 三、使用方法(前端调用例子)
<?php
require_once 'db_connect.php'; // 包含 $conn
require_once 'diagnose_function.php'; // 上述函数文件
$user_symptoms = ['咳嗽', '痰多', '口渴'];
$tongue = '黄腻';
$pulse = ['滑'];
$result = diagnose_from_db($conn, $user_symptoms, $tongue, $pulse);
echo "建议证型:{$result['diagnosis']}<br>";
echo "推荐方剂:{$result['formula']}<br>";
echo "匹配得分:{$result['score']}";
?>
📌 四、注意事项
symptoms与pulse字段需为 JSON 格式,如:["咳","痰"]。- 支持模糊匹配(如“咳嗽”能匹配“咳”规则)。
- 支持评分机制,可未来扩展多候选方案。
是否需要我帮你:
✅ 整理 diagnose_function.php 文件?
✅ 增加“多候选结果排序”?
✅ 整合 HTML 表单前端 + 显示匹配分析?
告诉我你的下一步目标,我可以快速生成整套!

Leave a Reply