Php Codeigniter-algorithm to generate string base from database data

Good Night guys, how are things? Let's get to my problem.

I have the data saved in this way in the bank: database

Basically a project has terms related to it. Terms in turn may possess synonyms.

I want my return to be as follows (see print 2)

("$termo" OR "$sinonimo") AND ("$termo" OR "$sinonimo")

This case will only apply if I have 2 terms with 1 synonym each. It can happen that there is only one term without a synonym, or several terms and some with others without synonyms.

Here is an image of what the view would look like and how it should perform.

insert the description of the image here

In this example the first term has two synonyms, the second term only one.

What would be the best way to solve what I want. My knowledge is limited to php and JS (ajax) gambiars.

Grateful now

Author: Guto G, 2018-06-13