0

如何计算出现在结果集字段中的单个单词?

例子

编号| 我的领域
1 | 梨 苹果 桃 西瓜
2 | 酸橙葡萄梨西瓜

我想得到 6,因为有 6 个独特的词

我不需要快速查询,它只是一个很少执行的统计计算

谢谢!

4

3 回答 3

2

您可以在空格上拆分结果,然后将它们添加到数组中,例如

foreach($results as $result)
{
    $words = explode(" ", $result['myfield']);

    $array = array();
    foreach($words as $word)
       $array[$word] = true;

}   
    echo count($array);

可能是更好的方法,但这又快又脏

于 2012-06-26T23:31:43.820 回答
2
function uniqueWords ($result, $field) {
    $words = array();
    while ($row = mysql_fetch_assoc($result)) { /* or something else if you use PDO/mysqli/some ORM */
        $tmpWords = preg_split('/[\s,]+/', $row[$field]);
        foreach ($tmpWords as $tmpWord) {
            if (!in_array($tmpWord, $words))
                $words[] = $tmpWord;
        }
    }

    return count($words);
}
于 2012-06-26T23:46:13.220 回答
1

我想不出一个纯粹的 SQL 解决方案——MySQL 真的不喜欢将单行拆分为多行。

PHP 版本很简单:

$sql="CREATE TEMPORARY TABLE words (word VARCHAR(100) PRIMARY KEY)";
//run this according to your DB access framework

$sql="SELECT myfield FROM mytable";
//run this according to your DB access framework
while (true) {
  //fetch a row into $row according to your DB access framework
  if (!$row) break;
  $words=preg_split('/[\s,]+/',$row['myfield']);
  foreach ($words as $word) {
    //Escape $word according to your DB access framework or use a prepared query
    $sql="INSERT IGNORE INTO words VALUES('$word')";
    //run this according to your DB access framework
  }
}

$sql="SELECT count(*) AS wordcount FROM words";
//run this according to your DB access framework, the result is what you want


$sql="DROP TABLE words";
//run this according to your DB access framework
于 2012-06-26T23:31:00.843 回答