echo当前行号csv php

时间:2016-03-24 23:38:53

标签: php csv row

我搜索了其他答案,但它们都是基于mysql或过于复杂..

我的脚本工作正常,但我会看到回显行号与foreach部分,其中我回显结果(其中iam采取这是最终找到行号,所以我可以添加删除行/行命令);

function ImportCSV2Array($filename)
{
$row = 0;
$col = 0;

$handle = @fopen($filename, "r");
if ($handle) 
{
    while (($row = fgetcsv($handle, 4096)) !== false) 
    {
        if (empty($fields)) 
        {
            $fields = $row;
            continue;
        }

        foreach ($row as $k=>$value) 
        {
            $results[$col][$fields[$k]] = $value;
        }
        $col++;
        unset($row);
    }
    if (!feof($handle)) 
    {
        echo "Error: unexpected fgets() failn";
    }
    fclose($handle);
}

return $results;

}

$filename = "file.csv";
$csvArray = ImportCSV2Array($filename);

foreach ($csvArray as $row)
{

echo " From: <input type=text name=from value='".$row['from']."'>";
echo "To: <input type=text name=to value='".$row['to']."'>";
echo whatwouldiput-here for line number?;

}

1 个答案:

答案 0 :(得分:0)

要保留索引,您只需执行此操作:

$i = 1;
foreach ($csvArray as $row)
{
   echo " From: <input type=text name=from value='".$row['from']."'>";
   echo "To: <input type=text name=to value='".$row['to']."'>";
   echo "Line number: ".$i;
   $i++;
}