I’m trying to create a list using a loop within a loop. I have 3 tables.
T1: faculty
T2: keywords
T3: facID, keywordID
I’ve created a select statement to cross join the rows and spit out something like this:
Faculty Name A
keyword-a keyword-b keyword-c
Faculty Name B
keyword-a keyword-d keyword-f
Everything works great except I need to add commas to the keyword list and my code isn’t doing the trick. My keywords are still looping through without the comma.
<?php while ($row = mysql_fetch_assoc($result)) { ?>
<?php if ($row['facID'] !== $lastID ) { ?>
<?php echo $row['facname']; ?><br />
<?php $lastID = $row['facID']; ?>
<?php } ?>
<?php $kwords = array();
foreach($row as $k => $v) {
if (strpos($k, 'kword') === 0) {
$kwords[] = $v;
}
}
echo implode(', ', $kwords);
} ?>
Any suggestions? I’m a noob and I’m hoping it’s something very obvious!
There seem to be a few issues with your code, so I’ll try to address them all.
First, you have a lot of opening and closing
<?php>tags, and it’s really messing with the readability of your code. Consider keeping as much code as possible contained into a single<?php>code block. For example, instead of this:…you can consolidate all of that PHP code into this:
Next, you’re not outputting any sort of visual break after echoing out your
implode()ed array. This would lead to the next heading being output on the same line as the output of your previous heading. For example, your first two headings will end up like this:Notice how
Faculty Name Bis at the end of the line of keywords?Finally, I think the problem you’re reporting is that you’re getting two keywords that are linked together. For example, if you had two rows of data with the same facility id, one with keywords
keyword-aandkeyword-band another withkeyword-candkeyword-d, you would see that output visually without a comma betweenkeyword-bandkeyword-c.In other words, instead of this:
…you’re instead seeing this:
This is also caused by the lack of a visual break between
implodeed lines, but I believe the problem is deeper than that. I believe you want all keywords for a given facility to be shown on a single line, not broken across multiple lines. For that, you need to move where you reinitialize your array so that it gets reinitialized at the same time you switch to a new heading. Try something like this:This still isn’t the best code, but you can refactor it.
The idea here is that the array gets output and reset every time the facility changes, so that the array encompasses all keywords for that facility and they all get output together, rather than being reported only as part of the database row they were returned with. After the loop completes, you have to manually report the last row since the usual reporting is taken care of within the loop.