注意:未定义的偏移量:file.php中第33行的1


Notice: Undefined offset: 1 in file.php on line 33

以下php代码:


<?php
$fopen = fopen("tasklistout.csv","r");
while(!feof($fopen))
{
    $line = fgets($fopen);
    echo "'r'n't<tr>";
    $piece_array = preg_split("/['s,]+/",$line);
    for ($forvar = 1; $forvar <= 5; $forvar++)
    {
        $array_index = $forvar - 1;
        echo "'r'n't't<td>" . $piece_array[$array_index] . "</td>";
    }
    echo "'r'n't</tr>'r'n";
}
fclose($fopen);
?>

产生以下错误:(在4个不同的场合)


注意:未定义的偏移量:第33行上file.php中的1


在以下HTML文档中:

<!doctype html>
<html lang="en">
   <head>
     <meta charset="utf-8">
     <title>Lab_11-Objective_01--Tables</title>
     <meta name="description" content="HTML 'table' element usage for Lab 11 Objective 01">
     <meta name="author" content="Charles E Lentz">
     <link rel="stylesheet" href="stylesheet.css">
   </head>
   <body>
   <table>
    <tr>
        <th>Image Name</th>
        <th>PID</th>
        <th>Session Name</th>
        <th>Session#</th>
        <th>Mem Usage</th>
    </tr>
    <?php
    $fopen = fopen("tasklistout.csv","r");
    while(!feof($fopen))
    {
        $line = fgets($fopen);
        echo "'r'n't<tr>";
        $piece_array = preg_split("/['s,]+/",$line);
        for ($forvar = 1; $forvar <= 5; $forvar++)
        {
            $array_index = $forvar - 1;
            echo "'r'n't't<td>" . $piece_array[$array_index] . "</td>";
        }
        echo "'r'n't</tr>'r'n";
    }
    fclose($fopen);
    ?>
   </table>
   </body>
</html>

如何修复此错误?

Undefined offset错误表示该变量中的数组项不存在。这表明问题在您的代码中更加突出,应该在哪里创建数组(但不是)。例如,preg_split("/['s,]+/",$line);行可能就是这里的问题。

要查找,请添加此行:

var_dump($piece_array);

在这条线路之后

$piece_array = preg_split("/['s,]+/",$line);

如果你需要进一步的帮助,将结果作为编辑发布,我会尽力帮助你。

csv文件末尾有一行空行
使用issetempty检查数组中是否存在索引
您可以使用foreach循环和file函数来代替while循环。请参阅我的示例代码。

<?php
  // read entire file into an array
  $lines  = file( "tasklistout.csv" );
  // loop through each line
  foreach( $lines as $line ) {
    // remove whitespace from line
    $line = trim( $line );
    // make sure that line is not empty
    if ( $line ) {
      // split line with comma or space
      $piece_array  = preg_split( "/['s,]+/", $line );
      // make sure that array contains at least 1 value
      if ( !empty( $piece_array ) ) {
        echo "'r'n't<tr>";
        for( $i = 0; $i < 5; $i++ ) {
          if ( isset( $piece_array[$i] ) ) {
            echo "'r'n't't<td>".$piece_array[$i]."</td>";
          }
          else {
            echo "'r'n't't<td>&nbsp;</td>";
          }
        }
        echo "'r'n't</tr>'r'n";
      }
    }
  }
?>

正如sergiu所建议的,.csv文件的格式可能没有包含五个逗号(可能只有一个)

您应该尝试使用foreach循环来实现这一点,从而避免数组索引(嗯,有点)。但首先要查看var_dump$piece_array是否为空,否则您可能需要检查.csv文件

相关文章: