如何在PHP中查找单词组合 [英] How To Find Words Combination In Php

查看:60
本文介绍了如何在PHP中查找单词组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组

$new_array=array('c','a','m','t','p');

现在我想找到单词表中存在的单词组合.

Now I want to find the words combination which exists in the words table.

我试图实现但没有成功.

I have tried to achieve but not succeeded.

这是我的php代码.

                        $words = array();
                $set = powerSet($new_array,2);

    $mysql = new mysqli("localhost","root","","startup");
$sql = "SELECT wordid from words WHERE lemma = '%s'" ;

foreach ($set as $key => $value)
{
    $word = implode("", $value);
    $wordPermutation = permute($word);

    foreach($wordPermutation as $keyWord)
    {
        if(!in_array($keyWord, $words))
        {
            if($result = $mysql->query(sprintf($sql,$keyWord)))

            {
                    var_dump(sprintf($sql,$keyWord));
                if($result->num_rows > 0)
                {
                    $words[] = $keyWord;
                }
           }
    }
}
}

print_r($words);


function powerSet($in, $minLength = 1, $max = 10) {
    $count = count ( $in );
    $members = pow ( 2, $count );
    $return = array ();
    for($i = 0; $i < $members; $i ++) {
        $b = sprintf ( "%0" . $count . "b", $i );
        $out = array ();
        for($j = 0; $j < $count; $j ++) {
            if ($b {$j} == '1')
                $out [] = $in [$j];
        }
        if (count ( $out ) >= $minLength && count ( $out ) <= $max) {
            $return [] = $out;
        }

    }
    return $return;
}


function permute($str) {
    if (strlen($str) < 2) {
        return array($str);
    }
    $permutations = array();
    $tail = substr($str, 1);
    foreach (permute($tail) as $permutation) {
        $length = strlen($permutation);
        for ($i = 0; $i <= $length; $i++) {
            $permutations[] = substr($permutation, 0, $i) . $str[0] . substr($permutation, $i);
        }
    }
    return $permutations;
}

我只想从表中存在的数组中找到那些组合.

I want to find only those combination from the array which exists in the table .

我的代码正在提取所有组合

My code is fetching all the combination

推荐答案

我可能对此有误解,但您不能为此使用单个数据库查询吗?

I might have mis-understood this but couldn't you use a single database query for this?

例如:

   SELECT wordid FROM `words` WHERE lemma LIKE ("%c%") OR lemma LIKE ("%a%") OR lemma LIKE ("%m%") OR lemma LIKE ("%t%") OR lemma LIKE ("%p%") 

这样,您将获得一个包含所有指定字符的单词的单词ID数组.

That way you'll get an array of wordids for any words containing any of the specified characters.

我会将其添加为评论,但没有足够的代表.

I'd add it as a comment but not enough rep yet.

这篇关于如何在PHP中查找单词组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆