Skip to content
Advertisement

Loop through associative array resulting from mysqli_fetch_assoc

I am new in the web development family and I really need help on that problem. The requirement is to get a list of video with their tags. I have 3 tables in the DB – one for videos, one for tags, and one intermediate table video_tags.

Here is my query to get datas from DB tables in order to list videos with their tags:

JavaScript

Then I execute this query:

JavaScript

So I got an associative array $item_row. Finally, I organize all the data in html table with a do/while loop:

JavaScript

However, the list has repetitive lines coz’ there are several tags for one video so you will get as many lines for one video as the tags that video has. I tried a foreach loop on the associative array.

JavaScript

But when I dumps information on the variable, I can see that the $key lists all the fields available from the DB in a row for all the 374 rows, and $value lists all the values in succession too. Exemple of the var_dump($item_row)

JavaScript

Is it possible to get an associative array like the following one:

JavaScript

Otherwise, I don’t see how I can do to avoid lines repetition for each tag of each video.

Thanks a lot for an answer.

Advertisement

Answer

To solve this you can manipulate your data to get something like a “parent => child” relationship (movies as parents and tags as children). Like so

JavaScript

And use it like so

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement