0

我有一段代码可以计算给定 .txt 文件中的单词,但由于某些原因,我收到以下错误并且没有给出结果。我不明白出了什么问题:

Warning: arsort() expects parameter 1 to be array, null given in /Applications/MAMP/htdocs/test-php-oop/class.wordcounter.php on line 20

Warning: Invalid argument supplied for foreach() in /Applications/MAMP/htdocs/test-php-oop/class.wordcounter.php on line 21

<?php // index.php
    include_once("class.wordcounter.php");
    $wc = new WordCounter("words.txt");
    $wc->count(WordCounter::DESC);
?>


<?php //class.wordcounter.php

class WordCounter {

    const ASC = 1;
    const DESC = 2;

    private $words;

    function __contruct($filename) {
        $file_content = file_get_contents($filename);
        $this->words = (array_count_values(str_word_count(strtolower($file_content),1)));

    }

    public function count($order) {
        if ($order == self::ASC)
            asort($this->words);
        else if ($order == self::DESC)
            arsort($this->words);
        foreach ($this->words as $key => $val)
            echo $key . " = " . $val . "<br/>";
    }

}

?>
4

4 回答 4

2

我发现了错误,__construct方法拼写错误!

这是更正后的代码,它可以工作:

<?php // index.php
    include_once("class.wordcounter.php");
    $wc = new WordCounter("words.txt");
    $wc->count(WordCounter::DESC);
?>


<?php //class.wordcounter.php

class WordCounter {

    const ASC = 1;
    const DESC = 2;

    private $words;

    function __construct($filename) {
        $file_content = file_get_contents($filename);
        $this->words = (array_count_values(str_word_count(strtolower($file_content),1)));

    }

    public function count($order) {
        if ($order == self::ASC)
            asort($this->words);
        else if ($order == self::DESC)
            arsort($this->words);
        foreach ($this->words as $key => $val)
            echo $key . " = " . $val . "<br/>";
    }

}

?>
于 2013-05-30T12:16:22.083 回答
0

尝试这个,

<?php
$no_of_words = 0;
str_replace(" ","",file_get_contents("/filename.txt"),$no_of_words);
echo $no_of_words;
?>
于 2013-05-30T12:21:09.847 回答
0

看起来脚本无法获取指定的文件。请尝试使用绝对 URL 并让我知道它是否有效。

更改此行:

$wc = new WordCounter("http://your_domain/your_path/words.txt");
于 2013-05-30T12:05:56.280 回答
0

你确定那file_get_contents()实际上是在返回一些东西吗?仅仅因为您在那里看到文件并不意味着 PHP 肯定可以访问它。

于 2013-05-30T12:07:36.643 回答