2012-05-01 95 views
1

我已经使用了以下问题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行的文本在DB

预期结果:

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

那么,你想添加数组在一起? –

+0

是的,我确实有30000个阵列 – Rob

回答

2

我没有你手头上的数据库,所以我会通过一个数组步进证明:

[[email protected] ~]$ 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); 

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

为了使这一去为你的使用情况,与同时更换foreach()循环,通过你的表步骤:

$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; 
} 
1

我会这样做:创建一个称为单词的新表,将每一行从数据库中拉出,循环遍历它并分解字符串并在数据中插入每个单词,并可选择存储数据(如主表id),以便随后获取有关上下文或词最额外的统计,如果你处理很多行和大型数据集,这可能不会是

那么你可以使用SQL来建立自己的计数等的最佳选择

1

PHP数组可以作为地图。所以你所要做的就是获取每一行的数据,维护单个数组作为关键字和数量作为值的数组映射。每当您看到密钥存在时,只需添加到计数中,或者添加具有相应计数的新密钥。

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