PHP访问指定数组索引展示数据 添加字段标识保留历史记录
问题说明
本项目共包含3个PHP文件,分别为index.php、processor.php和viewsubmission.php。
其中index.php与processor.php运行效果完全符合预期,问题仅出现在viewsubmission.php文件中。
运行该文件时仅能展示无字段标识的原始数据,效果如下:
期望实现的效果是从文本文件读取的每条对应数据前展示字段说明文字,预期效果如下:
需要解决两个核心问题:
- 如何访问数组特定索引,在对应数据前添加字段说明文本
- 如何在展示新提交数据时,不删除、不覆盖已展示的历史数据集
现有代码
index.php(表单页面代码)
<form action = "Processor.php" method = "post" enctype="multipart/form-data"> Student ID:<input type="text" name="studentId"><br> Student Name: <input type="text" name="studentName"><br> Activity Number: <input type="text" name="activityNumber"><br> Comment: <input type="text" name="comment"><br> File Upload (doc,docx, & pdf files only):<br><input type="file" name="fileupload"> <br><br> <button type="submit">Submit File</button> </form>
Processor.php(表单处理写入文件代码)
//creating the name of the file $newFileName = uniqid('',true) . "." . $FileExt; //identify file destination $fileDst = "uploads/" . $newFileName; move_uploaded_file($TempFile, $fileDst); //Write data in textfile $file = fopen("uploads/data.txt", "a"); fwrite($file, $_POST['studentId'] . "\n"); fwrite($file, $_POST['studentName'] . "\n"); fwrite($file, $_POST['activityNumber'] . "\n"); fwrite($file, $_POST['comment'] . "\n"); fwrite($file, $fileDst . "\n"); fclose($file); echo "<br><br>>New file Location: " . $fileDst . "<br>"; echo "Record Saved...";
viewsubmission.php(存在问题的读取展示代码)
<?php $filePath = "uploads/data.txt"; $content = file_get_contents($filePath); $values = explode("\n", $content); echo "<hr>"; $numberofData = 0; foreach($values as $val){ echo $val . "<br>"; $numberofData++; } $numberofData--; echo "<hr>";
解决方案
问题原因
每次表单提交会固定往data.txt写入5行顺序固定的数据:学号、姓名、活动编号、备注、上传文件路径,读取时按每5个元素为一组拆分,即可对应到字段;写入文件时已经使用a追加模式,本身不会覆盖历史数据,只需要遍历所有分组即可展示全部历史记录。
修改后的viewsubmission.php完整代码:
<?php $filePath = "uploads/data.txt"; $content = file_get_contents($filePath); // 过滤换行分割产生的空元素,避免索引错位 $values = array_filter(explode("\n", $content), function($item){ return trim($item) !== ''; }); // 重置数组索引 $values = array_values($values); // 字段映射,顺序必须和Processor.php写入顺序完全一致 $fields = [ 'Student ID', 'Student Name', 'Activity Number', 'Comment', 'File Path' ]; $fieldPerRecord = count($fields); echo "<hr>"; // 每次步进5个元素,遍历所有历史提交记录 for($i = 0; $i < count($values); $i += $fieldPerRecord){ // 单条记录内按索引匹配字段名和值 for($j = 0; $j < $fieldPerRecord; $j++){ echo $fields[$j] . ": " . $values[$i + $j] . "<br>"; } echo "<hr>"; }
内容的提问来源于stack exchange,提问作者Newbie
相关产品推荐
相关产品推荐

