我有文字:
$a = I wanna eat apple , and banana .
我要得到那个句子的每个单词和标点符号:
$b = explode(' ', strtolower(trim($a)));
爆炸的结果是数组。我有一个词表上的db有字段:
id, word和typewords全部小写。但是db中没有标点符号。我想要搜索db中的每个单词来获取单词的类型,所以我想要得到的最终结果是:
words/typeofwords
= 我/n想要/v吃/v苹果/n,/和/p香蕉/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);
但是它不工作,请帮助我,谢谢!
试试这个:
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];
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);
}
假设函数形参是一个数组,但它是一个字符串。
编辑:在您的函数中,您将$word
视为数组以及字符串。决定你想要什么并重新编码你的函数