0

我的 csv 文件中有 568 行,我的 for 循环看起来像这样

$csv = array();
$file = fopen('names.csv', 'r');

while (($result = fgetcsv($file)) !== false)
{
    $csv[] = $result;
}

fclose($file);

for ($row = 0; $row < 568; $row++)
{
echo "Serial no:<br/>";
echo "Name:".$csv[$row][1]."";
}

我想要这样的输出......

Serial no: 1
Name: Blah blah 1
Serial no: 2
Name: Blah blah 2
............
............
Serial no: 10
Name: Blah blah 10

对于每 10 行,我想要连续 1 到 10 .. 一旦完成 10 行,我想要一条水平线..

我的意思是我想打印

echo "<hr>";

每10行..

谁能帮我?谢谢

4

2 回答 2

2

This should work :

for ($row = 0; $row < 568; $row++) {
    echo "Serial no:<br/>";
    echo "Name:".$csv[$row][1];
    echo (($row+1)%10 == 0) ? '<hr>' : '<br />';
}

Explanation :

  • You don't need that ."" at the end of your "Name" line.
  • $row + 1 : instead of $row to avoid printing an <hr> after the first element (pos 0)
  • echo (condition) ? res1 : res 2; is like if (condition) echo res1; else echo res2;

But the real good way to do this would be :

$file = fopen('names.csv', 'r');
$i = 1;

while (($result = fgetcsv($file)) !== false) {
    echo "Serial no:" .$i. "<br/>";
    echo "Name:".$result[1];
    echo ($i == 1) ? '<hr>' : '<br />';
    $i = ($i%10)+1;
}

fclose($file);
于 2012-08-04T17:30:43.413 回答
0
$csv = array();
$file = fopen('names.csv', 'r');

while (($result = fgetcsv($file)) !== false)
{
    $csv[] = $result;
}

fclose($file);

for ($row = 0; $row < 568; $row++)
{
echo "Serial no:<br/>";
echo "Name:".$csv[$row][1]."";
   if ((int) $row % 10 === 0)
    {
        echo '<hr>';
    } 
}

应该做的伎俩:)

于 2012-08-04T17:29:02.160 回答