I want to generate two word combination from the word with the same category. Example I have this table:
+--------------+----------+
| 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 |
+-------------------------+----------+
But I have no idea how to do that. This is my code, and this code just combine all word without category filter.
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);
2
Answers
your current getAllCombinations function will give you reverse duplcates since you are iterating on all indexes inside a nested loop.
I think the answer here is using a basic for loop as follows
notice that the function should receive the array of results the same way it came from the DB. meaning:
with this method, you won’t get any duplicates since you won’t iterate on the same rows twice. hope it helped.
I can advice the MySQL solution for this problem:
result:
test SQL code here