gpt4 book ai didi

php - 从 PHP 中的 CSV 文件中删除当前迭代行

转载 作者:行者123 更新时间:2023-12-04 02:02:19 24 4
gpt4 key购买 nike

我想从 CSV 文件中删除当前迭代行,假设我的 CSV 文件中有 5 行(1、2、3、4、5),我打开文件时使用 foreach 逐行迭代,当涉及到第 3 行时,应从 CSV 文件中删除第 3 行和其他 1、2、4、5 行在相同迭代时将相同。我不想使用跳过第三次迭代并将其保存到另一个文件中,而不是重命名文件名。那么,任何人都可以帮助我如何在 PHP 中执行此操作?

假设,像删除当前行的SQL命令,PHP有没有?

谢谢。

最佳答案

您需要具有写入文件的权限。如果删除一行,则必须保存文件。由于您也不希望有任何空行,因此您需要读取整个文件。

我建议获取文件内容,并按行拆分成一个数组。使用 explode 函数,您可以通过换行符(最有可能是“\n”)拆分内容。因此,将存在一个包含 csv 文件每一行的数组。现在您可以简单地从数组中删除该行并从中创建一个字符串,然后将更改的内容保存回 csv 文件。

// get csv content into string variable
$csvContent = file_get_contents(__DIR__ . "/yourfile.csv");
// create array out of csv, limited by PHP_EOL wich determines the systems line break
// this means, every line in the csv file will be represended by an array key and its value
$csvArray = explode(PHP_EOL, $csvContent);

// unset the 3th csv line.
unset($csvArray[2]); // keep in mind array starts at 0, so third line is array key 2

// from here on you can manipulate the array $csvArray as you like.
// add lines, remove lines or just use the given content for future operations.
// you can also iterate over the array with: foreach ($csvArray as $line => $value) {}

// create string out of modified csv array
$csvContent = implode(PHP_EOL, $csvArray);
// save result back into the csv file
file_put_contents( __DIR__ . "/yourfile.csv", $csvContent);

检查 implode/explode php 函数文档:

http://php.net/manual/en/function.implode.php

http://php.net/manual/en/function.explode.php

关于php - 从 PHP 中的 CSV 文件中删除当前迭代行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46364076/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com