PHP 错误:未定义的偏移量:1
看起来这可能是处理数组时的错误,但我无法弄清楚。我真的刚刚开始接触 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>";
}
?>
这是文本文件中的内容:
Instruments|What kind of instruments do you like?
Music|What type of music do you like best?
我应该澄清: 错误出现在第 20 行,或者显示 list($key,$v) =explode...
的位置
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 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...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你在某处有一个空行。这就是为什么
explode()
将仅返回一个空的 $key,但没有任何内容可分配给 $v。这就是它打印该通知的时间。您可以稍微重写它以忽略此类情况:
这也将避免最终 $data 数组中出现空条目。
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.You can rewrite it a bit to ignore such cases:
This will also avoid an empty entry in your final $data array.
试试这个:
Try this:
您可以尝试使用
array_pad()
函数。在编写爆炸函数的地方使用它。
You could try to use the
array_pad()
function.Use it where you wrote the explode function.