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
ifchains: 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
calculateQuestionScorefunction can be called anywhere in your app.
Fixing the "Undefined Function" Error
That fatal error almost always happens for one of these reasons:
- Function is defined after it's called: Make sure
calculateQuestionScoreis declared before you try to use it (like in the demo above). - Typos: Double-check the function name spelling when you call it (e.g.,
calculateQuestionScorevscalculateQuestionScores). - Scope issues: If you're using the function inside a class or another function, make sure it's accessible (e.g., use
globalor 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
$userSubmissionsonly contains valid question IDs, and answers aren't empty.
内容的提问来源于stack exchange,提问作者Solomon G
相关产品推荐
相关产品推荐

