【发布时间】:2016-08-10 06:30:16
【问题描述】:
我有一个数组
$new_array=array('c','a','m','t','p');
现在我想找到单词表中存在的单词组合。
我尝试过,但没有成功。
这是我的 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;
}
我只想从表中存在的数组中找到那些组合。
我的代码正在获取所有组合
【问题讨论】:
标签: php combinations permutation