【发布时间】:2019-12-12 16:47:06
【问题描述】:
我正在尝试从 .txt 文件中逐行读取值,然后将其存储在数组中,以便稍后在程序中使用这些值。 问题是,当我在循环内打印我的数组时,它打印得很好,但是当我尝试在循环外打印它时,它什么也没打印。
txt 文件:
I/P 电压 : 212.0
I/P 故障电压 : 212.0
O/P 电压 : 212.0
O/P 电流:000
I/P 频率:50.0
电池电压:13.7
温度:28.0
UPS 状态:00001001
我的代码:
数组名是$UPS_respond
<?php
# -----------------------------------------------------
# Read value from file
# -----------------------------------------------------
$i = 0 ;
$file = fopen("/usr/local/bin/UpsResult.txt","r"); //i open my file to read it
$dot = 0;
while( !feof( $file ) ) {
$y = fgets($file);
$dot = strpos($y,':')+1;
$x = substr($y, $dot);
$UPS_respond = array($i => $x);
echo "inside of Loop => ".'$UPS_respond['.$i.'] :'.$UPS_respond[$i]."<br>";
$i++;
}
fclose( $file );
echo "Ouside of Loop => ".$UPS_respond[$i]."<br>";
?>
结果:
inside of Loop => $UPS_respond[0] : 213.5
inside of Loop => $UPS_respond[1] : 213.5
inside of Loop => $UPS_respond[2] : 213.0
inside of Loop => $UPS_respond[3] : 000
inside of Loop => $UPS_respond[4] : 50.0
inside of Loop => $UPS_respond[5] : 13.7
inside of Loop => $UPS_respond[6] : 28.0
inside of Loop => $UPS_respond[7] : 00001001
Ouside of Loop =>
【问题讨论】:
-
echo 'Well bugger me, turns out after the loop $i has the following value: ' . $i; -
如果你输入
echo $i,你会发现它的值是8,因为它在退出循环之前最后一次递增,并且数组没有分配给该键的值。
标签: php arrays variable-assignment assign