我的问题很具体。我是一名初学php程序员,我很难在PHP中编制数组数据结构。该程序正在从输入文件(input.txt
)读取并将结果存储到与该项目的关键字相同的数组中。虽然input.txt
文件有数字为了方便,我必须将它们存储为字符串(我的程序需要大于32位的整数)。但是,当我尝试将它们索引为$a["3"]
时,出现错误Undefined offset: 3
。我tried $a['3']
,$a[3]
都具有相同的结果。但奇怪的是,我能够正确地索引$a["2"]
这个数组中的最后一个元素!请帮忙。PHP:关联数组索引问题
这里是输入文本文件:
3
4
5
1
2
这里是代码段:
<?php
ignore_user_abort(true);
set_time_limit(0);
$temp=0;
$a= array();
$file= fopen("input.txt","r") or exit("unable to open file");
while(!feof($file)){
$temp=fgets($file);
$a[$temp]=$temp;
}
fclose($file);
echo "<br>The array is .. ";
foreach ($a as $key => $item) {
echo "<br> Key => item =",$key."=>",$item ;
echo "<br>Manual array test ",$a["3"]; // This line demonstrates the problem.
}
echo "<br>Manual array test ",$a["2"]; // This one has no error! So basically only the last element is being indexed correctly
//echo "<br> No of 2 sums is ",twoSum($a,4,6);
?>
'$ temp =(int)fgets($ file);',no? – raina77ow
你应该得到使用''的语法错误,当你连接字符串时你应该使用'.'。例如这里:'echo'
key => item =“,$ key。”=>“,$ item;'它应该是'echo”
Key => item =“。$ key。”=>“。$ item;' –
@ raina77ow OP要存储整数> INT_MAX,所以需要使用字符串类型。 – Benubird