2014-04-29 186 views
1

我的問題很具體。我是一名初學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); 
?> 
+1

'$ temp =(int)fgets($ file);',no? – raina77ow

+1

你應該得到使用''的語法錯誤,當你連接字符串時你應該使用'.'。例如這裏:'echo'
key => item =「,$ key。」=>「,$ item;'它應該是'echo」
Key => item =「。$ key。」=>「。$ item;' –

+0

@ raina77ow OP要存儲整數> INT_MAX,所以需要使用字符串類型。 – Benubird

回答

3

新線值還獲得存儲在$temptrim$temp數據如下,並嘗試

$temp = trim(fgets($file)); 
+0

謝謝你的哥們! –

+0

不客氣,很高興它的工作。 –