How to display multiple records with same id in html table in single row(in <td>)?
codeigniter, html, php
Solution
A quick way to approach this would be to modify your MySQL query to use `GROUP_CONCAT(hobbies)` to group all of a user's hobbies together. The query would look something like:
SELECT
id, name, GROUP_CONCAT(hobbies) AS hobbies
FROM
your_table
GROUP BY
id
This will group all of a user's hobbies in a comma-delimited list. To display it, you can use PHP's `explode()` and iterate over that:
foreach ($results as $row) {
echo '<tr>';
echo '<td>' . $row->id . '</td>';
echo '<td>' . $row->name . '</td>';
echo '<td>';
$hobbies = explode(',', $row->hobbies);
foreach ($hobbies as $hobby) {
// output each hobby and decorate/separate them however you'd like
echo $hobby . '<br />';
}
echo '</td>';
echo '</tr>';
}
If you don't want the inner loop (or the ending `<br />` that will pad the hobbies), you can use `str_replace()` instead:
echo str_replace(',', '<br />', $result['hobbies']);
Problem
I have sql data result set having records as follows ``` id | name | hobbies ------------------------------------ 1 | RAVI | PLAYING CRICKET ------------------------------------ 1 | RAVI | LISTENING MUSIC ------------------------------------ 2 | REENA | BADMINTON ------------------------------------ ``` I am displaying this data in view by using html table. Whereas my requirement is, I want to display as follows ``` id | name | hobbies ------------------------------------ 1 | RAVI | PLAYING CRICKET | | LISTENING MUSIC ------------------------------------ 2 | REENA | BADMINTON ------------------------------------ ``` meaning I want to display records with id 1 into one `<td>` I am using php `foreach` loop to display result. How can I achieve this? My current code is as follows and is results into same as my first table whereas I want my view as in the second table. ``` <table class="table table-striped"> <tr > <th>ID</th> <th>Name</th> <th>Hobbies</th> </tr> foreach($result as $row) { echo "<tr> <td>".$row->id."</td> <td>". $row->name."</td> <td>". $row->hobbies."</td> </tr>"; } </table> ```