我有一个.txt文件和一个.php文件
。.txt:
15118553;1315239266;0;1;EURUSD;1.4111;0;0;1315239282;1.4109;0;0;-27;0;
。.php:
<?php
$text = file_get_contents('test.txt', true);
$sir = explode(";", $text);
$d=count($sir);
for($i=0; $i<=$d ; $i++)
echo "string = ". $i ."-------". $sir[$i]. "<br>" ;
?>
在本地主机中:
string = 0-------15118553
string = 1-------1315239266
string = 2-------0
string = 3-------1
string = 4-------EURUSD
string = 5-------1.4111
string = 6-------0
string = 7-------0
string = 8-------1315239282
string = 9-------1.4109
string = 10-------0
string = 11-------0
string = 12--------27
string = 13-------0
string = 14-------
Notice: Undefined offset: 15 in C:'xampp'htdocs'test'index.php on line 7
string = 15-------
为什么它们显示 15 个字符串?在 txt 文件中只有 13 个字符串。如何修复此错误?
为什么是"未定义的偏移量":
将其更改为:
for($i=0; $i < $d ; $i++)
因为你开始从零开始计算元素,而不是从一开始计算元素。
为什么选择14:
因为您的输入字符串以分隔符结尾,所以爆炸后您会得到 jne 额外的字符串。
您可以循环到 $d - 1
,也可以使用 if
条件来检查此字符串是否为空字符串。
该错误意味着数组中没有偏移量"15$sir。
您应该迭代直到 $count - 1
.
但是,由于您是跳过数组此类问题的初学者,因此请始终使用foreach。
尝试如下:
foreach($str as $strValue) {
echo "string = ". $strValue. "<br>" ;
}
for($i=0; $i<$d ; $i++)
循环将从0
运行到n-1
因为数组从索引 0 开始。
所以,当你自己数线时,你开始:"1,2,3,4,..."当数组以"0, 1, 2, 3 ..."开头时。所以你出现了第 15 行,但由于$d[15] = null;
而崩溃
此外,你写了"$i<=$d"
.$d[14] = ",因为它介于行尾;
和行尾之间。您可以echo "Count : ".$d
,并查看Count : 14
。
为了更好地理解:
Line[x] | Array[x] | count($sir) | Array <= $d // $d = count($sir);
1 0 14 TRUE
2 1 14 TRUE
3 2 14 TRUE
4 3 14 TRUE
5 4 14 TRUE
6 5 14 TRUE
7 6 14 TRUE
8 7 14 TRUE
9 8 14 TRUE
10 9 14 TRUE
11 10 14 TRUE
12 11 14 TRUE
13 12 14 TRUE
14 13 14 TRUE
15 14 14 TRUE // --> Array[14] == "". PHP prints empty string, but doesn't crash.
16 15 14 FALSE // --> Array[15] == null. PHP crashes.
这就是为什么$i(这里等于 Array[x](在崩溃之前堆叠到 $i = 15。
你可能想写:
for($i = 0;$i < $d-1;i++)
{
// do something;
}