PHP 错误:未定义的偏移量:1

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5400332/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 21:16:33  来源:igfitidea点击:

PHP Error: Undefined offset: 1

phpundefined

提问by eightonrose

It seems like this might be an error dealing with arrays, but I can't figure it out. I'm really just starting with PHP and this is getting to be a little intimidating. Any help would be greatly appreciated! here is my code:

看起来这可能是处理数组的错误,但我无法弄清楚。我真的只是从 PHP 开始,这有点令人生畏。任何帮助将不胜感激!这是我的代码:

<?php echo "<h1>Choose a Poll!</h1>";

$read = file('poll_topics.txt');   
$data = array( );           
foreach($read as $lines){           
    list($key,$v) = explode("|","$lines");          
    $data[$key] = $v;
}

foreach ($data as $k=>$desc){               
    echo "<ul><li><a href='take_a_poll.php?poll=$k'>$k</a> - $desc </li></ul>";
}

?>

Here is what is in the text file:

这是文本文件中的内容:

  Instruments|What kind of instruments do you like?
  Music|What type of music do you like best?

I should clarify: The error is line 20, or where it says list($key,$v) = explode...

我应该澄清:错误是第 20 行,或者它说的地方 list($key,$v) = explode...

回答by mario

You have an empty line somewhere. That's why explode()will return only an empty $key, but have nothing to assign to the $v. And that's when it prints that notice.

你在某处有一个空行。这就是为什么explode()只会返回一个空的 $key,而没有任何东西可以分配给 $v。这就是它打印该通知的时候。

You can rewrite it a bit to ignore such cases:

您可以稍微重写一下以忽略此类情况:

foreach ($read as $lines) {
    $key = strtok($lines, "|");
    $v = strtok("|");
    if ($v) {
        $data[$key] = $v;
    }
}

This will also avoid an empty entry in your final $data array.

这也将避免在最终的 $data 数组中出现空条目。

回答by lucifurious

Try this:

尝试这个:

<?php 

echo "<h1>Choose a Poll!</h1>";
$_fileData = file_get_contents('poll_topics.txt'); 
$_results = array();

if ( ! empty( $_fileData ) )
{
    foreach ( $_fileData as $_line ) 
    {
        $_split = explode( '|', $_line );

        //  Many ways to do this:
        //  if ( !empty( $_split ) && 2 == count( $_split ) ) then no error else error
        //  or...
        if ( isset( $_split[0], $_split[1]  ) )
        {
            $_key = $_split[0];
            $_value = $_split[1];

            if ( null !== $_key && null !== $_value )
            {
                $_results[ $_key ] = $_value;
                    //  or  $_results[] = array( $_key => $_value ); if key can be duplicated
            }

        }
    }
}

回答by Keziah Kitone

You could try to use the array_pad()function. Use it where you wrote the explode function.

您可以尝试使用该array_pad()功能。在您编写爆炸函数的地方使用它。

$_split = array_pad(explode( '|', $_line ), numberOfElementsInArray, null);