PHP 注意:未定义偏移量:1 读取数据时带数组

PHP Notice: Undefined offset: 1 with array when reading data(PHP 注意:未定义偏移量:1 读取数据时带数组)
本文介绍了PHP 注意:未定义偏移量: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.net 可能从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 读取数据时带数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

DeepL的翻译效果还是很强大的,如果我们要用php实现DeepL翻译调用,该怎么办呢?以下是代码示例,希望能够帮到需要的朋友。 在这里需要注意,这个DeepL的账户和api申请比较难,不支持中国大陆申请,需要拥有香港或者海外信用卡才行,没账号的话,目前某宝可以
PHP通过phpspreadsheet导入Excel日期,导入系统后,全部变为了4开头的几位数字,这是为什么呢?原因很简单,将Excel的时间设置问文本,我们就能看到该日期本来的数值,上图对应的数值为: 要怎么解决呢?进行数据转换就行,这里可以封装方法,或者用第三方的
mediatemple - can#39;t send email using codeigniter(mediatemple - 无法使用 codeigniter 发送电子邮件)
Laravel Gmail Configuration Error(Laravel Gmail 配置错误)
Problem with using PHPMailer for SMTP(将 PHPMailer 用于 SMTP 的问题)
Issue on how to setup SMTP using PHPMailer in GoDaddy server(关于如何在 GoDaddy 服务器中使用 PHPMailer 设置 SMTP 的问题)