PHP注意:读取数据时,未定义的偏移量为1,数组为1 [英] PHP Notice: Undefined offset: 1 with array when reading data

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

问题描述

我收到这个PHP错误:

I am getting this PHP error:

PHP Notice:  Undefined offset: 1

以下是引用它的PHP代码:

Here is the PHP code that throws it:

$file_handle = fopen($path."/Summary/data.txt","r"); //open text file
$data = array(); // create new array map

while (!feof($file_handle) ) {
    $line_of_text = fgets($file_handle); // read in each line
    $parts = array_map('trim', explode(':', $line_of_text, 2)); 
    // separates line_of_text by ':' trim strings for extra space
    $data[$parts[0]] = $parts[1]; 
    // map the resulting parts into array 
    //$results('NAME_BEFORE_:') = VALUE_AFTER_:
}

这个错误是什么意思?什么原因导致这个错误?

What does this error mean? What causes this error?

推荐答案

更改

$data[$parts[0]] = $parts[1];

if ( ! isset($parts[1])) {
   $parts[1] = null;
}

$data[$parts[0]] = $parts[1];

或简单地:

$data[$parts[0]] = isset($parts[1]) ? $parts[1] : null;

不是你的文件的每一行都有一个冒号,因此它会在其上爆炸返回一个大小的数组1。

Not every line of your file has a colon in it and therefore explode on it returns an array of size 1.

根据 php。来自爆炸的净可能返回值

According to php.net possible return values from explode:


返回通过拆分字符串创建的字符串数组参数由分隔符形成的边界。

Returns an array of strings created by splitting the string parameter on boundaries formed by the delimiter.

如果分隔符为空字符串(),则explode()将返回FALSE。如果分隔符包含一个不包含在字符串中的值并且使用负极限,则将返回一个空数组,否则将返回包含字符串的数组。

If delimiter is an empty string (""), explode() will return FALSE. If delimiter contains a value that is not contained in string and a negative limit is used, then an empty array will be returned, otherwise an array containing string will be returned.

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

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