简体   繁体   English

使用for循环根据用户输入在数组中递增单个值

[英]Increment single value in an array based on user entry using for loop

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. 我希望每当用户按下保存到csv文件中的提交按钮时,就可以在数组中增加单个值。 However, every time I try the number stays at 1. 但是,每次我尝试将数字保持为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. 谢谢。

The basic strategy is to read the existing records from the CSV file, then use that info to generate a new ID. 基本策略是从CSV文件读取现有记录,然后使用该信息生成新ID。 The new ID could either be based on either: 新的ID可以基于以下任意一个:

  1. The total number of records, or 记录总数,或
  2. The largest current ID stored. 当前存储的最大ID。

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 . 在您现有的代码中, for循环似乎是不必要的,因为它是人为生成一个数字-该数字始终为0因为count($count) 始终返回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 ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM