[英]PHP: Generate word combination from the word with the same category
我想從具有相同類別的單詞中生成兩個單詞組合。 示例我有這張表:
+--------------+----------+
| Word | Category |
+--------------+----------+
| human | social |
| politic | social |
| law | social |
| artificial | science |
| intelligence | science |
+--------------+----------+
and I want the output like this:
+-------------------------+----------+
| Word | Category |
+-------------------------+----------+
| human-law | social |
| human-politic | social |
| politic-law | social |
| artificial-intelligence | science |
+-------------------------+----------+
但我不知道該怎么做。 這是我的代碼,這個代碼只是結合了所有沒有類別過濾器的單詞。
Model Class(md_classification):
function getWords(){
$stat = $this->db->query("SELECT DISTINCT(word), category from tb_words group by word, category");
return $stat->result_array();
}
function getAllCombinations($array){
$combinations = array();
foreach ($array as $x)
foreach ($array as $y) {
if ($x != $y && !in_array($y . '-' . $x, $combinations))
array_push($combinations, $x . '-' . $y);
}
return $combinations;
}
Controller:
$getWord = $this->md_classification->getWords();
foreach ($getWord as $row) {
$word[] = $row['word'];
$category[] = $row['category'];
}
$result = $this->md_classification->getAllCombinations($word);
您當前的 getAllCombinations function 將為您提供反向重復,因為您在嵌套循環內的所有索引上進行迭代。 我認為這里的答案是使用基本的 for 循環,如下所示
function getAllCombinations($array){
$combinations = array();
for ($i = 0; $i < sizeof($array); $i++)
for ($j = $i+1; $j < sizeof($array); $j++)
if ($array[$i]['category'] == $array[$j]['category'])
array_push($combinations, $array[$i]['word'] . '-' . $array[$j]['word']);
return $combinations;
}
請注意,function 應該以與來自 DB 的方式相同的方式接收結果數組。 意義:
$result = $this->md_classification->getAllCombinations($getWord);
使用這種方法,您不會得到任何重復項,因為您不會對相同的行進行兩次迭代。 希望它有所幫助。
對於這個問題,我可以建議 MySQL 解決方案:
select concat(w.Word, ' - ', w1.Word) Words, w.Category
from words w
join words w1 on w.Category = w1.Category
where w.Word < w1.Word
;
結果:
+===========================+==========+
| Words | Category |
+===========================+==========+
| human - politic | social |
+---------------------------+----------+
| law - politic | social |
+---------------------------+----------+
| human - law | social |
+---------------------------+----------+
| artificial - intelligence | science |
+---------------------------+----------+
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.