问题
I am learning PHP and I want to know how to do an inner loop or nested loop with records in PHP. I will appreciate if somebody explains me how to do this type of loop in PHP.
I have this table in MySQL [

I just want to create a report table in PHP that looks like this:
So far, I know how to do a current loop with the code below but how could I do in the same loop and inner loop to show dishes like table above. I know how to create the format (table, spaces, etc) I just need the PHP logic to do this in the best way.
<?php
do { ?>
Table in here
<?php } while ($selecc = mysqli_fetch_assoc($conmenu)); ?>
回答1:
The clean/direct approach should be something like this:
SELECT Client, Option, GROUP_CONCAT(Dish SEPARATOR ', ')
FROM table_name
GROUP BY Client, Option
Then with your data already grouped and glued together, just print your strings in a single loop of the result set.
Using a do {} while ()
is of no benefit here.
Here's an untested snippet...
if ($conmenu) {
echo '<table>';
echo '<tr><td>Client</td><td>Option</td><td>Dishes</td></tr>';
while ($row = mysqli_fetch_assoc($conmenu)) {
echo '<tr><td>' , implode('</td><td>', $row) , '</td></tr>';
}
echo '</table>';
}
For the record:
The maximum permitted result length in bytes for the GROUP_CONCAT() function. The default is 1024.
https://dev.mysql.com/doc/refman/8.0/en/server-system-variables.html#sysvar_group_concat_max_len
Also, $conmenu
is iterable, so you could use a foreach instead of a while loop.
foreach ($conmenu as $row) { ...
If you want to do it the hard way...
SELECT Client, Option, Dish
FROM table_name
ORDER BY Client, Option
Then... (untested)
if ($conmenu) {
echo '<table>';
echo '<tr><td>Client</td><td>Option</td><td>Dishes</td></tr>';
$group = null;
foreach ($conmenu as $row) {
if ($group !== $row['Client'] . '_' . $row['Option']) {
if ($group !== null) {
echo '</td></tr>';
}
echo '<tr><td>' , implode('</td><td>', $row);
} else {
echo ", " , $row['Dish'];
}
$group = $row['Client'] . '_' . $row['Option']; // update group
}
echo '</td></tr>'; // close final iteration
echo '</table>';
}
来源:https://stackoverflow.com/questions/54204805/how-to-do-an-inner-loop-of-records-in-php