【问题标题】:search array for duplicates php搜索重复的数组php
【发布时间】:2013-08-30 03:26:22
【问题描述】:

自从我使用 PHP 已经有好几年了,我已经有点生疏了。 我正在尝试编写一个快速脚本,该脚本将打开一个大文件并将其拆分为一个数组,然后在每个值中查找类似的事件。例如,该文件由以下内容组成:

Chapter 1. The Beginning 
 Art. 1.1 The story of the apple
 Art. 1.2 The story of the banana
 Art. 1.3 The story of the pear
Chapter 2. The middle
 Art. 1.1 The apple gets eaten
 Art. 1.2 The banana gets split
 Art. 1.3 Looks like the end for the pear!
Chapter 3. The End
…

我希望脚本自动告诉我其中两个值中包含字符串“apple”并返回“Art. 1.1 The Story of the apple”和“Art. 1.1 The apple gets eating”,然后香蕉和梨也是如此。

我不想在数组中搜索特定字符串,我只需要它来计算出现次数并返回内容和位置。

我已经获得了打开文件然后将其拆分为数组的脚本。只是无法弄清楚如何找到类似的事件。

<?php
$file = fopen("./index.txt", "r");
$blah = array();
while (!feof($file)) {
   $blah[] = fgets($file);
}
fclose($file);

var_dump($blah);
?>

任何帮助将不胜感激。

【问题讨论】:

  • “只是不知道如何找到类似的事件” -- 好吧,这就是手头的问题......到目前为止你尝试了什么?
  • 您的文件有多大?将它全部保存在内存中对于 PHP 来说可能太多了。此外,即使在您的简短样本中(故事、结束、获取、该、的),也重复了许多其他词。您提议的代码如何知道要计算哪些?
  • 没有那么大。该数组有 1650 个值。
  • 我尝试过的所有东西都需要一个实际值来搜索。我知道这可能有一个简单的解决方案,它现在只是在逃避我。我知道在这个简短的例子中有多次出现。实际文件中并没有很多常见的“the”、“of”等...
  • 另外,仅供参考:在这种情况下,从 $file = fopen...fclose... 的所有内容都可以替换为一行:$blah = file("./index.txt")

标签: php arrays recursive-regex find-occurrences


【解决方案1】:

这个解决方案并不完美,因为它会计算文本中的每个单词,因此您可能需要对其进行修改以更好地满足您的需求,但它可以准确统计文件中每个单词被提及的次数以及到底是哪几行。

$blah = file('./index.txt') ;

$stats = array();
foreach ($blah as $key=>$row) {
    $words = array_map('trim', explode(' ', $row));
    foreach ($words as $word)
        if (empty($stats[$word]))  {
            $stats[$word]['rows'] = $key.", ";
            $stats[$word]['count'] = 1;
        } else {
            $stats[$word]['rows'] .= $key.", ";
            $stats[$word]['count']++;
        }
}
print_r($stats);

我希望这个想法能帮助您继续前进并进一步完善它以更好地满足您的需求!

【讨论】:

  • 谢谢您,先生,这对您有很大帮助!
猜你喜欢
  • 2019-05-08
  • 1970-01-01
  • 2013-09-08
  • 2013-09-20
  • 1970-01-01
  • 2013-03-08
  • 2017-09-24
  • 2018-01-16
  • 2014-09-07
相关资源
最近更新 更多