开发者

PHP Error: Undefined offset: 1

开发者 https://www.devze.com 2023-02-18 08:31 出处:网络
It seems like this might be an error dealing with arrays, but I can\'t figure it out. I\'m really just starti开发者_运维百科ng with PHP and this is getting to be a little intimidating.

It seems like this might be an error dealing with arrays, but I can't figure it out. I'm really just starti开发者_运维百科ng 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...


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;
    }
}

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


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
            }

        }
    }
}


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

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

精彩评论

暂无评论...
验证码 换一张
取 消