function diagnose_from_json

以下是一个完整的 PHP 函数,用于:

✅ 从 diagnosis_rules.json 读取规则
✅ 自动匹配用户提交的症状 / 舌象 / 脉象
✅ 返回最匹配的中医证型与方剂


✅ 一、匹配函数 diagnose_from_json()

<?php
function diagnose_from_json($user_symptoms, $tongue_input, $pulse_input) {
    // 读取 JSON 文件
    $json = file_get_contents('diagnosis_rules.json');
    $rules = json_decode($json, true);

    $best_match = null;
    $max_score = 0;

    foreach ($rules as $rule) {
        $score = 0;

        // 匹配症状(关键词模糊匹配)
        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++;
        }

        // 匹配脉象(关键词模糊匹配)
        if (!empty($pulse_input) && is_array($rule['pulse'])) {
            foreach ($rule['pulse'] as $keyword) {
                foreach ($pulse_input as $p) {
                    if (strpos($p, $keyword) !== false) {
                        $score++;
                        break;
                    }
                }
            }
        }

        // 更新最佳匹配
        if ($score > $max_score) {
            $max_score = $score;
            $best_match = $rule;
        }
    }

    return $best_match ?: ['diagnosis' => '无匹配证型', 'formula' => '请人工判断'];
}
?>

✅ 二、使用方式(示例)

<?php
require 'diagnose_function.php'; // 如果你将上面函数独立为 diagnose_function.php

// 假设用户提交的表单数据
$user_symptoms = ['咳嗽', '痰多', '口渴'];
$tongue = '黄腻';
$pulse = ['滑'];

$result = diagnose_from_json($user_symptoms, $tongue, $pulse);

echo "建议证型:{$result['diagnosis']}<br>";
echo "推荐方剂:{$result['formula']}";
?>

📁 三、diagnosis_rules.json 示例内容格式:

[
  {
    "diagnosis": "痰热咳嗽",
    "formula": "清金化痰汤",
    "symptoms": ["咳", "痰"],
    "tongue": "黄腻",
    "pulse": ["滑", "数"]
  },
  ...
]

如你希望将此功能:

  • 💻 集成到前台问诊系统
  • 🔄 自动从 MySQL 而非 JSON 获取规则
  • 📊 返回多个候选证型 + 匹配分数

我也可以立即扩展以上功能。是否需要我继续?


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *