来自foreach输出的PHP操作

时间:2013-09-14 12:33:41

标签: php variables foreach

我有这个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进行竞争。 的 BUT !!我认为包含:''LOSE''(在END处有一个空格)。

1 个答案:

答案 0 :(得分:-2)

以下是一种方法,记住以下内容:Read a plain text file with 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>';
}