0

私はこのphpコードを持っています。これはすでに試しました:

<?php 
foreach (glob("somefolder/*/*/wdl.txt") as $somevar) {include $somevar;} 
?>

このコードはこれを出力します:

WIN DRAW LOSE WIN WIN DRAW WIN DRAW

ここで、勝った回数、引き分けた回数、負けた回数を示すこの出力変数を作成したいと思います。

たとえば、変数をエコーするときの変数は、4 WIN のために4出力$winsします。

どうすればそれができますか?どうも。

各 wdl.txt には、 LOSE または DRAW または WIN のみが含まれます。 しかし!!''LOSE'' (末尾にスペースあり) が含まれていると思います。

4

1 に答える 1

-2

これを行う方法は次のとおりです。php でプレーン テキスト ファイルを読み取る

<?php
$foo = '';
foreach (glob("somefolder/*/*/wdl.txt") as $somevar) {
  //If required: include $somevar;
  $foo .= file_get_contents($somevar);
}

if (!empty($foo)) {
    $wins = preg_match_all('~WIN~iUs', $foo, $matches);
    $draw = preg_match_all('~DRAW~iUs', $foo, $matches);
    $lose = preg_match_all('~LOSE~iUs', $foo, $matches);

    print 'Wins: ' . $wins;
    print 'Draw: ' . $draw;
    print 'Lose: ' . $lose;
}
?>

そして別のオプション。

<?php
/**
 * Results class.
 */
class Result
{
    /**
     * Magic method set propertie.
     */
    public function __set($name, $value)
    {
        $this->$name = $value;
    }

    /**
     * Magic method get propertie.
     */
    public function __get($name)
    {
        return $this->$name;
    }
}

//Variables.
$stat   = '';
$result = new Result();
$path   = getcwd() . '/*.txt';

//Loop trough $path files.
foreach (glob($path) as $file) {
    //Get the content from the stat file.
    $stat = file_get_contents($file);

    //If the file whith stat is empty, continue to next file.
    if (empty($stat)) {
        continue;
    }

    //Check if we already have a stat result in object.
    if (isset($result->$stat)) {
        //Add it up.
        $result->$stat++;
    } else {
        //Create the stat and asign 1 to it.
        $result->$stat = 1;
    }   
}

/**
 * Get results manually.
 */
print 'Win: ' . $result->win . '<br>';
print 'Lose: ' . $result->lose . '<br>';
print 'Draw: ' . $result->draw . '<br>';

/**
 * Or trough loop.
 */
//Get all properties from the Result object.
$results = get_object_vars($result);

//Loop trough the properties and print the values.
foreach($results as $key => $value) {
    print $key . ': ' . $value . '<br>';
}
于 2013-09-14T12:40:43.873 に答える