問題描述
我收到此 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 讀取數據時帶數組的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!