我有这个php代码,我已经准备好了:
<?php
foreach (glob("somefolder/*/*/wdl.txt") as $somevar) {include $somevar;}
?>
这段代码输出这个:
WIN DRAW LOSE WIN WIN DRAW WIN DRAW
现在我想制作这个输出变量,告诉我有多少赢了,多少平局,有多少输了。
例如,当我回显$wins
变量时,变量将具有 4 个 WIN 的输出 4
我该怎么做?谢谢。
每个WDL.txt只输或平或赢。但!!我认为包含:"LOSE"(末尾有一个空格)。
这里有一种方法可以做到这一点,牢记以下几点, 使用 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>';
}