搜索数据库中的单词数组

时间:2014-06-24 21:03:42

标签: php mysql

我有文字:

$a = I wanna eat apple , and banana .

我想得到那句话的每一句话和标点符号:

$b = explode(' ', strtolower(trim($a)));

爆炸的结果是数组。 我在db上有一个单词表,其中包含以下字段:

id, word and typewords
全部为小写。但是对于标点符号,db中不存在。 我想搜索db中的每个单词来获取单词的类型,所以我想得到的最终结果是: words/typeofwords =
I/n wanna/v eat/v apple/n ,/, and/p banana/n ./.
这是代码:

function getWord ($word){
$i = 0 ;
$query = mysql_query("SELECT typewords FROM words WHERE word = '$word' ");
    while ($row = mysql_fetch_array($query)) {
         $word[$i] = $row['typewords'];
        $i++;
    }
    return $word;
}

echo $b.'/'.getWord($b);

但它不起作用,请帮助我,谢谢!

3 个答案:

答案 0 :(得分:1)

试试这个:

function getWord($words){
    $association = array();
    foreach($words as $word)
    {
        $query = mysql_query("SELECT typewords FROM words WHERE word = '$word' ");
        if($row = mysql_fetch_array($query)) 
            $association[$word] = $row['typewords'];
        elseif(preg_match('/[\.\,\:\;\?\!]/',$word)==1)
            $association[$word] = $word;
    }
    return $association;
}

$typewords = getWord($b);
foreach($b as $w)
    echo $w.'/'.$typewords[$w];

答案 1 :(得分:0)

您假设函数参数是一个数组,但它是一个字符串。

编辑:在您的函数中,您将$word视为数组和字符串。决定你想要什么并重新编写你的功能。

答案 2 :(得分:0)

function getWord($word){

    // concat the word your searching for with the result
    // http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_concat
    $query = mysql_query("SELECT CONCAT(word,'/',typewords) as this_result FROM words WHERE word = '$word' ");
    $row = mysql_fetch_array($query);
    return $row['this_result']." ";  // added a space at the end.
}

// loop through the $b array and send each to the function
foreach($b as $searchword) {
    echo getWord($searchword);
}
相关问题