How To Find Words Combination In Php

為{幸葍}努か 提交于 2019-12-20 07:30:21

问题


I have a array

$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.

this is my php code .

                        $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


回答1:


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

Such as:

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

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.



来源:https://stackoverflow.com/questions/36695335/how-to-find-words-combination-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!