0

我有这个 php 代码,我已经尝试过:

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

这段代码输出:

WIN DRAW LOSE WIN WIN DRAW WIN DRAW

现在我想让这个输出变量告诉我赢了多少,平局多少,输了多少。

例如,当我回显该变量时,该$wins变量将输出4,因为4 WIN。

我怎么能这样做?谢谢。

每个 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 回答