gpt4 book ai didi

PHP 通知 : Undefined offset: 1 with array when reading data

转载 作者:IT老高 更新时间:2023-10-28 12:06:12 25 4
gpt4 key购买 nike

我收到这个 PHP 错误:

PHP Notice:  Undefined offset: 1

这是抛出它的 PHP 代码:

$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_:
}

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

最佳答案

改变

$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 的数组。

根据php.net possible return values from explode :

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

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 通知 : Undefined offset: 1 with array when reading data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17456325/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com