dongyao2001 2018-04-27 02:34
浏览 43
已采纳

使用for循环基于用户输入增加数组中的单个值

I'm not entirely sure how to do this and I've been stuck trying to figure this out. I want to be able to increment a single value inside an array every time a user presses a submit button which gets saved into a csv file. However, every time I try the number stays at 1.

Could I get some guidance? Here's what I have:

<?php $name = $_POST["Name"];
$grade = $_POST["Grade"];
$handle = fopen("users.csv", "a+t");

if (!$handle) {
    die("error, can't open file!");
}
if (!flock($handle, LOCK_EX)) {
    die("lock error!");
}
$count = 10;
for ($i = 0; $i < count($count); $i++) {
    $count++; 
    fputcsv($handle, array($i++, $name, $grade)); }
fseek($handle, 0);

while (!feof($handle)) { 

$record = fgetcsv($handle);
?>
<div>
    ID Number: <?php echo $record[0]; ?><br/>
    Name: <?php echo $record[1]; ?><br/>
    Grade: <?php echo $record[2]; ?><br/>
</div> }

Thank you.

  • 写回答

1条回答 默认 最新

  • doulianglou0898 2018-04-27 03:09
    关注

    The basic strategy is to read the existing records from the CSV file, then use that info to generate a new ID. The new ID could either be based on either:

    1. The total number of records, or
    2. The largest current ID stored.

    In your existing code, the for loop seems unnecessary since it is artificially generating a number - which will always be 0 because count($count) always returns 1.

    I've cleaned up the code and added some comments:

    $name = $_POST["Name"];
    $grade = $_POST["Grade"];
    $handle = fopen("users.csv", "a+t");
    
    if (!$handle) die("error, can't open file!");
    if (!flock($handle, LOCK_EX)) die("lock error!");
    
    $records = array();
    while (!feof($handle))
        $records[] = fgetcsv($handle);
    
    // 1. Use this to find the number of elements
    $count = count($records);
    
    // 2. Use this to find the largest current ID
    $max = $count > 0 ? max(array_column($records, 0)) : 0;
    
    // Our new ID should be based on (1) or (2) above
    $newId = $max + 1;
    
    fputcsv($handle, array($newId, $name, $grade));
    
    fseek($handle, 0);
    while (!feof($handle)) { 
        $record = fgetcsv($handle);
        // ... print out your <div> here ...
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog