PHP 错误:未定义的偏移量:1 [英] PHP Error: Undefined offset: 1

查看:34
本文介绍了PHP 错误:未定义的偏移量:1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

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

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

推荐答案

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

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:

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

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

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

这篇关于PHP 错误:未定义的偏移量:1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆