问题
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