【问题标题】:Sort and count instances of words in a database对数据库中单词的实例进行排序和计数
【发布时间】:2012-05-11 05:47:56
【问题描述】:

我用过下面的问题php: sort and count instances of words in a given string

我的数据库中有一个带有文本字段的表,我想对该字段中的单词进行一些分析,但我需要合并结果

ID | Text Field
1  | happy beautiful happy lines pear gin happy lines rock happy lines pear 
2  | happy lines pear gin happy lines rock happy lines pear 

我现在有一个看起来像这样的数组(但它是每行)

第 1 行

Array (
    [happy] => 4
    [beautiful] => 1
    [lines] => 3
    [pear] => 2
    [gin] => 1
    [rock] => 1 )

第 2 行

Array (
    [happy] => 4
    [lines] => 3
    [pear] => 2
    [gin] => 1
    [rock] => 1 )

如何对所有行执行此操作以组合结果 - 数据库中有 30000 行文本

预期结果:

Array (
    [happy] => 8
    [beautiful] => 1
    [lines] => 6
    [pear] => 4
    [gin] => 2
    [rock] => 2 )

【问题讨论】:

  • 那么,你想把数组加在一起吗?
  • 是的,我有——不过有 30000 个数组

标签: php string


【解决方案1】:

我手头没有你的数据库,所以我将通过一个数组来演示:

[ghoti@pc ~]$ cat doit.php
#!/usr/local/bin/php
<?php

$a=array(
  '1' => "happy beautiful happy lines pear gin happy lines rock happy lines pear",
  '2' => "happy lines pear gin happy lines rock happy lines pear",
  '3' => "happy rock pear happy happy happy",
);

$wordlist=array();

foreach ($a as $index => $line) {
  foreach (explode(" ", $line) as $word) {
    $wordlist[$word]++;
  }
}

print_r($wordlist);

[ghoti@pc ~]$ ./doit.php
Array
(
    [happy] => 11
    [beautiful] => 1
    [lines] => 6
    [pear] => 5
    [gin] => 2
    [rock] => 3
)
[ghoti@pc ~]$ 

要使其适合您的用例,请将 foreach() 替换为遍历您的表的 while 循环:

$sql = "SELECT id,wordlist FROM yadda";
$result = db_query($sql);
while ($row = db_fetch_row($result)) {
  ...
}

我不知道您使用的是什么数据库服务器,所以我无法提供我知道适用于您的具体示例。

【讨论】:

    【解决方案2】:

    当您从数据库中获取每一行时,请保持运行总计

    $total = array();
    foreach($row as $word=>val){
        if(!isset($totals[$word])) $totals[$word] = 0;
        $totals[$word] += $val;
    }
    

    【讨论】:

      【解决方案3】:

      我会这样做:创建一个名为 words 的新表,将每一行从数据库中拉出,循环遍历它并分解字符串并将每个单词插入数据中,可选择存储诸如主表 id 之类的数据,以便您然后可以获得有关上下文或单词的大多数附加统计信息,如果您处理许多行和大型数据集,这可能不是最佳选择

      然后你可以使用 sql 来建立你的计数等

      【讨论】:

        【解决方案4】:

        您可以使用 SQL 直接计算字数。看看这个之前的回答:

        Using SQL to determine word count stats of a text field

        【讨论】:

          【解决方案5】:

          PHP 数组可以用作地图。因此,您所要做的就是获取每一行的数据,维护一个单词数组映射作为键,并将它们的计数作为值。每次看到键存在时,只需添加到计数中,否则添加具有相应计数的新键。

          $grandtotal = array();
          foreach($row as $key=>$val) {
           if(array_key_exists($key, $grandtotal)) {
            $grandtotal[$key] += $val;
           }
           else {
            $grandtotal[$key] = $val;
           }
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2015-06-25
            • 2021-12-12
            • 1970-01-01
            • 2020-09-05
            • 1970-01-01
            • 2017-09-08
            • 1970-01-01
            相关资源
            最近更新 更多