You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP数据库评分系统优化需求:简化多条件判断语句

Hey there! I totally get how frustrating those endless nested if statements can get—they turn into a maintenance nightmare real quick. Let's fix that for your scoring system with some cleaner, more scalable approaches:

1. Configuration-Driven Rule Mapping (Lightweight & Intuitive)

The easiest fix is to move all your scoring rules into a structured config (like a dictionary, JSON file, or even a database table) instead of hardcoding conditionals. This lets you look up scores directly based on user selections.

Example (Python):

# Store rules in a dictionary (you can also save this as JSON or pull from a DB)
scoring_rules = {
    "age": {
        "18-25": 10,
        "26-35": 15,
        "36-45": 12,
        "46+": 8
    },
    "education": {
        "high_school": 5,
        "bachelor": 15,
        "master": 20,
        "phd": 25
    },
    "work_experience": {
        "<1 year": 3,
        "1-3 years": 8,
        "3-5 years": 12,
        "5+ years": 18
    }
}

def calculate_total_score(user_choices):
    total = 0
    # Loop through each user selection and sum the matching scores
    for category, selection in user_choices.items():
        # Use .get() to handle invalid selections gracefully (default to 0)
        total += scoring_rules[category].get(selection, 0)
    return total

# Usage
user_selections = {"age": "26-35", "education": "master"}
print(calculate_total_score(user_selections))  # Output: 35 (15 + 20)

For Complex Combined Rules:

If you need to handle multi-condition bonuses (e.g., "age 26-35 + master's degree = extra 5 points"), extend the config to include condition sets:

bonus_rules = [
    {"conditions": {"age": "26-35", "education": "master"}, "bonus_score": 5},
    {"conditions": {"age": "18-25", "work_experience": "<1 year"}, "bonus_score": 3}
]

def calculate_with_bonuses(user_choices):
    total = calculate_total_score(user_choices)
    # Check each bonus rule
    for rule in bonus_rules:
        # Verify all conditions in the rule match the user's selections
        if all(user_choices.get(key) == value for key, value in rule["conditions"].items()):
            total += rule["bonus_score"]
    return total
2. Strategy Pattern (For Complex Per-Category Logic)

If some categories require more than just a simple value-to-score mapping (e.g., custom calculations or external checks), use the strategy pattern to encapsulate each category's logic separately. This keeps your code modular and easy to update.

Example (Python):

# Define separate scoring functions for each category
def score_age(age_range):
    # Add custom logic here if needed (e.g., adjust score based on other factors)
    return scoring_rules["age"].get(age_range, 0)

def score_education(edu_level):
    # Example: Extra points for STEM degrees (if you track that)
    base_score = scoring_rules["education"].get(edu_level, 0)
    if edu_level in ["master", "phd"] and user_major == "STEM":  # Assume user_major is available
        return base_score + 5
    return base_score

# Map categories to their respective scoring functions
scoring_strategies = {
    "age": score_age,
    "education": score_education,
    "work_experience": lambda exp: scoring_rules["work_experience"].get(exp, 0)
}

def calculate_score_with_strategy(user_choices):
    total = 0
    for category, selection in user_choices.items():
        strategy = scoring_strategies.get(category)
        if strategy:
            total += strategy(selection)
    return total

With this approach, you can update one category's logic without touching the rest—perfect for keeping your codebase maintainable.

3. Database-Stored Rules (For Dynamic Updates)

If your scoring rules need to change frequently (e.g., your team wants to adjust scores without redeploying code), store the rules directly in your database.

Example Database Schema:

  1. score_categories table:

    idname
    1age
    2education
    3work_experience
  2. score_rules table:

    idcategory_idcondition_valuescore
    1118-2510
    2126-3515
    32master20

Query to Calculate Total Score:

SELECT SUM(sr.score) AS total_score
FROM score_rules sr
JOIN score_categories sc ON sr.category_id = sc.id
WHERE 
    (sc.name = 'age' AND sr.condition_value = '26-35')
    OR (sc.name = 'education' AND sr.condition_value = 'master');

This way, you can update scores or add new rules directly in the database—no code changes required.

Which Approach Should You Pick?

  • Simple, static rules: Go with the configuration-driven mapping (fastest to implement).
  • Complex per-category logic: Use the strategy pattern (modular and easy to maintain).
  • Need dynamic rule updates: Use database-stored rules (most flexible for non-technical teams).

内容的提问来源于stack exchange,提问作者Xaris man

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:18:04