【问题标题】:Add data to a csv and increase one of the values将数据添加到 csv 并增加其中一个值
【发布时间】:2021-12-31 00:47:31
【问题描述】:

你好,我会试着解释清楚,这有点令人困惑

我有一个 .csv 文件,名为 users.csv,格式如下:

id name surname email

还有这些数据:

1 paul   harrison  test@test.com
2 robin  martinez  test@test.com
3 alma   halford   test@test.com

问题是我需要将表单中的数据引入到csv中,但是当我们从表单中获取数据时没有引入id元素,我该怎么做才能增加一个id并添加到同一行中 id 后面的数据是否相同?

<form style="text-align: center;" method="post">
    name: <input type="text" name="name">
    <br><br>
    surname: <input type="text" name="surname">
    <br><br>
    Email: <input type="email" name="mail">
    <br><br>
    Password: <input type="password" name="pwd">
    <br><br>
    smartphone: <input type="tel" name="smart">
    <br><br>
    city: <input type="text" name="city">
    <br><br>
    C.P: <input type="number" name="cp">
    <br><br>
    <input type="submit" name="send">
</form>

添加更多信息的想法是,每次向 users.csv 中添加数据时,csv 中的 id 列都会增加,每次我们在 csv 中写入数据时,id 文件都会增加一个。

【问题讨论】:

  • 好的,如果表单不知道id,您将如何在 CSV 中找到正确的行来添加新数据
  • 如果您向我们展示&lt;form&gt;将会很有用
  • 好的,所以你必须读取文件的每一行,在你进入一个新文件时写入不匹配的行。当您找到 namesurnameemail 的匹配项时,将新数据添加到该行,然后写入该行,然后将所有剩余的行写入文件。数据库更容易处理
  • 尝试不同的东西,是否可以从csv文件中选择最后一个id值并增加1?不知道该怎么做。

标签: php arrays forms associative-array


【解决方案1】:

如果你想像 SQL 那样实现自增行为,只需找到一个最大 ID 并将其增加一个即可。结果是新行的新标识符。

所以要找到最大值:

$csv = ''; // here you csv
$max = 0;
foreach (explode("\n", $csv) as $row) {
  foreach (explode("\t", $row) as $index => $col) {
    if ($index == 0 && (int)$col > $max)
      $max = (int)$col;
  }
}

因此,您将在$max 变量中获得最大 ID。正如我之前所说,只需将其增加一个,您就有新行的新标识符。

【讨论】:

    猜你喜欢
    • 2021-05-24
    • 2014-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-26
    相关资源
    最近更新 更多