2011-07-28 15 views
1

私はスクリプトを作成しているゲームに100のハイスコアを含むファイルを持っています。ファイルを読み込んで返している行を返す

1.2345, name1 
1.3456, name2 
1.4567, name3 

などです。

phpでは、新しいスコアが古いスコアよりも高い場合、私はそれを上書きすることができるので、phpの行の内容を取得する必要があります。また、どのライン番号nameXが表示されているかを知る必要があります。

私はこの作業をするためにどのPHP関数を調べるべきですか?

+3

あなたの自己を大いに好んで、データベースを使用し始める –

答えて

4

あなたは、このいずれかのfopenfreadまたはfileを使用することができます。個人的には、これはかなり小さいファイルで始まるように私はファイルを選択します。良い測定のために

$row = -1; 
$fl = file('/path/to/file'); 

if($fl) 
{ 
    foreach($fl as $i => $line) 
    { 
     // break the line in two. This can also be done through subst, but when 
     // the contents of the string are this simple, explode works just fine. 
     $pieces = explode(", ", $line); 
     if($pieces[ 1 ] == $name) 
     { 
      $row = $i; 
      break; 
     } 
    } 
    // $row is now the index of the row that the user is on. 
    // or it is -1. 
} 
else 
{ 
    // do something to handle inability to read file. 
} 

、fopenのアプローチ:

// create the file resource (or return false) 
$fl = fopen('/path/to/file', 'r'); 
if(!$fl) echo 'error'; /* handle error */ 

$row = -1; 
// reads the file line by line. 
while($line = fread($fl)) 
{ 
    // recognize this? 
    $pieces = explode(", ", $line); 
    if($pieces[ 1 ] == $name) 
    { 
     // ftell returns the current line number. 
     $row = ftell($fl); 
     break; 
    } 
} 
// yada yada yada 
+0

($ pieces [1] == $ name)ではないでしょうか? – bfavaretto

+0

@bfavarettoはい。一定。 – cwallenpoole

2

これは私が常に推奨しているリンクです。これまでこれまで失敗していませんでした。リンクから

Files in php

<?php 

// set file to read 
$file = '/usr/local/stuff/that/should/be/elsewhere/recipes/omelette.txt' or die('Could not read file!'); 
// read file into array 
$data = file($file) or die('Could not read file!'); 
// loop through array and print each line 
foreach ($data as $line) { 
    echo $line; 
} 

?> 
0

まず、あなたは、すべてのファイルの内容を読み出す必要があります。あなたが望む線を改造して、それらをまとめてファイルに戻します。ただし、スクリプトを同時に実行している場合は、パフォーマンスと構成が大幅に向上します。

関連する問題