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

PHP评分系统开发求助:需无冗余IF的Demo及解决未定义函数错误

Hey there! Let's sort out your PHP scoring system problem. The biggest pain point with messy if statements is solved by using a centralized configuration array to map questions to their valid answer sets and points. This keeps your code clean, scalable, and easy to update. I'll share a fully working demo, plus address that undefined function error you hit.

Working PHP Scoring System Demo

Core Idea: Rule-Based Configuration

Instead of writing endless if/else blocks, we'll store all scoring rules in an array. This way, adding or modifying questions only requires updating the array—no need to touch the core scoring logic.

<?php
// Step 1: Define your scoring rules in a single array
$scoringRules = [
    'question1' => [
        'valid_answers' => ['abc'], // Only this answer gets points
        'points' => 5
    ],
    'question2' => [
        'valid_answers' => ['bcd', 'cft'], // Multiple valid answers
        'points' => 10
    ],
    // Add more questions here easily
    'question3' => [
        'valid_answers' => ['xyz', '123'],
        'points' => 8
    ]
];

// Step 2: Create a reusable scoring function
function calculateQuestionScore(string $questionId, string $userAnswer, array $rules): int {
    // If the question isn't in our rules, return 0 points
    if (!array_key_exists($questionId, $rules)) {
        return 0;
    }

    $rule = $rules[$questionId];
    // Normalize answers to lowercase to avoid case sensitivity issues
    $normalizedUserAnswer = strtolower(trim($userAnswer));
    $normalizedValidAnswers = array_map('strtolower', $rule['valid_answers']);

    // Check if the user's answer is in the valid list
    return in_array($normalizedUserAnswer, $normalizedValidAnswers) ? $rule['points'] : 0;
}

// Step 3: Simulate user input (in real use, get this from $_POST/$_GET)
$userSubmissions = [
    'question1' => 'ABC', // Case-insensitive match works
    'question2' => 'cft',
    'question3' => '456' // Invalid answer, gets 0
];

// Step 4: Calculate total score
$totalScore = 0;
foreach ($userSubmissions as $question => $answer) {
    $totalScore += calculateQuestionScore($question, $answer, $scoringRules);
}

// Output the result
echo "Total Score: " . $totalScore; // Outputs 5 + 10 + 0 = 15
?>

Why This Works Better

  • No messy if chains: All rules live in one place—easy to audit and update.
  • Scalable: Add a new question by just adding a new entry to $scoringRules.
  • Case-insensitive: The code normalizes answers to lowercase, so "ABC" and "abc" both count.
  • Reusable function: The calculateQuestionScore function can be called anywhere in your app.

Fixing the "Undefined Function" Error

That fatal error almost always happens for one of these reasons:

  1. Function is defined after it's called: Make sure calculateQuestionScore is declared before you try to use it (like in the demo above).
  2. Typos: Double-check the function name spelling when you call it (e.g., calculateQuestionScore vs calculateQuestionScores).
  3. Scope issues: If you're using the function inside a class or another function, make sure it's accessible (e.g., use global or pass it as a callback if needed).

Quick Extensions You Might Want

  • Multi-select answers: If users can pick multiple options (e.g., "a,b,c"), split the answer string and check against valid combinations.
  • Variable points per answer: Modify the rules array to map specific answers to different points (e.g., 'answers' => ['abc' => 5, 'def' => 3]).
  • Input validation: Add checks to ensure $userSubmissions only contains valid question IDs, and answers aren't empty.

内容的提问来源于stack exchange,提问作者Solomon G

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:13:34