php 使用explode(...)后PHP数组中的“未定义偏移量”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19004588/
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 18:39:03  来源:igfitidea点击:

"Undefined offset" in PHP array after using explode(...)

php

提问by Tupan

Can u tell me why show me tons of notice ?

你能告诉我为什么要给我看成吨的通知吗?

I am new in php and don't understand where is my mistake, notices from line:

我是 php 新手,不明白我的错误在哪里,请注意:

<td>'.$columns[1].'</td> 

To line:

到线:

$sum+=$columns[2];

Here is my code:

这是我的代码:

<?php
         if(file_exists('data.txt'))
         {
             $result= file('data.txt');
             $sum='0';

             foreach($result as $value)
             {

                 $columns=explode('-', $value);

                 echo  '<tr>
                             <td>'.$columns[0].'</td>
                             <td>'.$columns[1].'</td>
                             <td>'.$columns[2].'</td>
                             <td>'.$kinds[trim($columns[3])].'</td>
                        </tr>';
                 $sum+=$columns[2];

             }
             echo '<tr>
                <td>--</td>
                <td>--</td>
                <td>' . $sum . ' </td>
                <td>--</td>
            </tr>'; 


         }             
         ?>

I am new in php and don't understand where is my mistake :( notices from line

我是 php 新手,不明白我的错误在哪里:( 行通知

<td>'.$columns[1].'</td> 

to line

到线

$sum+=$columns[2];

Here are the notices:

以下是通知:

Notice: Undefined offset: 3 in C:\xampp\htdocs\HomeworkOne\index.php on line 31 
Notice: Undefined index: in C:\xampp\htdocs\HomeworkOne\index.php on line 31
Notice: Undefined offset: 2 in C:\xampp\htdocs\HomeworkOne\index.php on line 33
Notice: Undefined offset: 1 in C:\xampp\htdocs\HomeworkOne\index.php on line 29
Notice: Undefined offset: 2 in C:\xampp\htdocs\HomeworkOne\index.php on line 30
Notice: Undefined offset: 3 in C:\xampp\htdocs\HomeworkOne\index.php on line 31
Notice: Undefined index: in C:\xampp\htdocs\HomeworkOne\index.php on line 31

回答by Pupil

You are using uninitialized variables. $columns[1], $columns[2]and $columns[3]are not getting values Please try this corrected code:

您正在使用未初始化的变量。 $columns[1],$columns[2]并且$columns[3]没有得到值请试试这个更正的代码:

<?php
if(file_exists('data.txt'))
{
    $result= file('data.txt');
    $sum='0';

    foreach($result as $value)
    {

        $columns=explode('-', $value);
        $kindsDisplay = (isset($columns[3]) && ! empty($kinds[trim($columns[3])])) ? $kinds[trim($columns[3])] : '';
        $one = isset($columns[1]) ? $columns[1] : '';
        $two = isset($columns[2]) ? $columns[2] : '';
        $sum+= isset($columns[2]) ? $columns[2] : 0;

        echo  '<tr>
                   <td>'.$columns[0].'</td>
                   <td>'.$columns[1].'</td>
                   <td>'.$columns[2].'</td>
                   <td>'.$kindsDisplay.'</td>
               </tr>';

    }

    echo '<tr>
              <td>--</td>
              <td>--</td>
              <td>' . $sum . ' </td>
              <td>--</td>
          </tr>'; 

} ?>

回答by Christoph Diegelmann

Some things to consider: a blank line at the end of the file could cause this if it only happens once (not each line).

需要考虑的一些事情:如果文件末尾的空行只发生一次(不是每一行),则可能会导致这种情况。

If you want to have default values in case your data is missing seperators you can add

如果您想在数据缺少分隔符的情况下使用默认值,您可以添加

$columns = $columns + array('default_for_key0', 'default1', 'default2', 'default3');

after explode().

之后explode()

回答by Daniel W.

This is an undefined offset:

这是一个未定义的偏移量:

$array[0] = "test1";
$array[1] = "test2";

echo $array[3];

You are better off using objects or arrays where you know whats inside.

最好使用知道内部内容的对象或数组。

To get rid use if's:

要摆脱使用 if :

$array[0] = "test1";
$array[1] = "test2";

if (array_key_exists(3, $array)) {
    echo $array[3];
}

The problem in your case:

你的情况的问题:

$columns = explode('-', $value);

The data you grep from the textfile is not 100% the format you expect, for example:

您从文本文件中提取的数据不是您期望的 100% 格式,例如:

aaaaa-bbbbbb-cccccc-ddddddd
aaaaa--cccccc-dddddd
aaaaa-ddddd

This means, you need to verify tha data you read is VALID and in the correct format.

这意味着,您需要验证您读取的数据是否有效且格式正确。

回答by René H?hle

You read every line of the data file. When you have a blank line you have no data in your $result.

您读取数据文件的每一行。当您有一个空行时,您的$result.

Then you try to explode on an empty string and columns[0]is not set.

然后您尝试在空字符串上爆炸并且columns[0]未设置。

Try to check if the array is not empty perhaps with

尝试检查数组是否不为空

if(count($columns) > 2) {

}

or check wheather the array is set.

或检查数组是否设置。

if(isset($columns[0])) {

}

otherwise you can fill the array with default data.

否则,您可以使用默认数据填充数组。

回答by Halcyon

Your data is probably not as sane as you think.

您的数据可能不像您想象的那么健全。

$columns=explode('-', "abc");
$columns[0]; // "abc";
$columns[1]; // gives: Undefined offset 1

Either ensure your data is what you expect, or explicitly try to find error cases, like a line with no -.

要么确保您的数据符合您的预期,要么明确尝试查找错误情况,例如没有-.

You can do count($columns)to find out how many columns there are.

您可以count($columns)找出有多少列。



Be very wary of constructions like:

非常警惕以下结构:

$kinds[trim($columns[3])]

You have 2 possible undefined offsets here. $columns[3]and $kinds[#index#]can both be undefined.

您在这里有 2 个可能的未定义偏移量。$columns[3]并且$kinds[#index#]都可以是未定义的。

回答by dareKevil

Try this way and you will see if you have 4 columns every time:

试试这种方式,你会看到每次都有 4 列:

<?php
if (file_exists('data.txt')) {
    $result= file('data.txt');
    $sum=0;

    foreach($result as $value) {
        $columns=explode('-', $value);
        echo  '<tr>';
        foreach ($columns as $key => $column) {
            echo '<td>'.$column.'</td>';
            if ($key == 2) $sum += $column;
        }
    echo '</tr>';
    echo '<tr><td>--</td><td>--</td><td>'.$sum.'</td><td>--</td></tr>'; 
}             
?>

回答by Satyam Saxena

First you will need to set $kinds as array. Secondly, check array keys before you use in the program else it will throw errors like below: http://d.pr/i/GzVk

首先,您需要将 $kinds 设置为数组。其次,在程序中使用之前检查数组键,否则它会抛出如下错误:http: //d.pr/i/GzVk

Check the revised code, I Hope this will helpful for you.

检查修改后的代码,我希望这对你有帮助。

<?php
if(file_exists('data.txt'))
{
$result= file('data.txt');
$sum='0';
$kinds = array();

foreach($result as $value)
{

$columns=explode('-', $value);

if(array_key_exists($columns[0], $columns)) {
echo '<td>'.$columns[0].'</td>';
}
if(isset($columns[1]) && array_key_exists($columns[1], $columns)) {
echo '<td>'.$columns[1].'</td>';
}

if(isset($columns[2]) && array_key_exists($columns[2], $columns)) {
echo '<td>'.$columns[2].'</td>';
$sum+=$columns[2];
}

if(isset($columns[3]) && array_key_exists($columns[3], $columns)) {
echo '<td>'.$kinds[trim($columns[3])].'</td>';
}

echo      '</tr>';


}
echo '<tr>
<td>--</td>
<td>--</td>
<td>' . $sum . ' </td>
<td>--</td>
</tr>';


}
?>