PHP星级统计页面无法通过键获取关联数组值问题求助
Hey there! Let's work through your problem—your main issue comes from hidden whitespace in your array keys, plus some logic gaps in your code. Here's how to fix it step by step:
Core Problem: Hidden Whitespace in Array Keys
When you use file($files) to read your text file, it preserves newline characters (like \n or \r\n) at the end of each line. That's why your array keys look like "2 " or "5 "—it's actually a rating plus a hidden newline, not just a space. When you try to access $vals["2"], it doesn't match the key with the hidden newline, hence the "Undefined offset" error.
Quick Fix for Clean Keys
Process each line with trim() to strip all whitespace (newlines, spaces, tabs) before counting:
$files = "../Question1.txt"; $lines = file($files); // Trim whitespace from every line to get clean rating values $lines = array_map('trim', $lines); $vals = array_count_values($lines);
Now your $vals array will have clean keys like "2" or "5", and you can access them directly with $vals["2"] without errors.
Fixing Your Stats Display Logic
Your current loop logic has a few issues (empty foreach, checking array indexes instead of ratings, broken HTML tags). Here's a simplified, working version of your stats display code:
<?php $counter = 1; $targetFile = "../Question1.txt"; if (file_exists($targetFile)) { $lines = file($targetFile); $lines = array_map('trim', $lines); $ratingCounts = array_count_values($lines); // Loop through ratings 1 to 5 to display counts for ($rating = 1; $rating <= 5; $rating++) { // Get count for current rating, default to 0 if not present $count = isset($ratingCounts[(string)$rating]) ? $ratingCounts[(string)$rating] : 0; echo "<td>" . ($count > 0 ? $count : "-") . "</td>"; } } else { // If file doesn't exist, display dashes for all ratings for ($rating = 1; $rating <= 5; $rating++) { echo "<td>-</td>"; } } ?>
Key Improvements in This Code:
- Uses
trim()to clean up rating values before counting - Directly loops through ratings 1-5 instead of iterating over raw file lines
- Uses
isset()to safely check if a rating exists in the count array (avoids undefined index errors) - Fixes broken HTML tags (closes
<td>properly) - Handles the case where the file doesn't exist gracefully
Testing the Fix
After applying this, you can verify your clean array with:
var_dump($ratingCounts);
You'll see keys like "2" instead of "2 ", and accessing $ratingCounts["2"] will return the correct count without errors.
内容的提问来源于stack exchange,提问作者twinaholic

