Reputation: 1708
I have the following piece of HTML in a PHP app with an array including Group and Items. First I want to sort them by Groups, then within Groups have Items separated by comma (Item1, Item2, Item3), without ending comma.
<dl>
<?php $groupname = '' ?>
<?php foreach ($product['product_filters'] as $product_filter) { ?>
<?php if ($groupname != $product_filter['group']) { ?>
<?php $groupname = $product_filter['group']; ?>
<?php echo '<dd>' . $product_filter['group'] . '</dd>'; ?>
<?php } ?>
<dt>
<?php echo $product_filter['name']; ?>
</dt>
<?php } ?>
</dl>
I want to have a the following result, but I don't know how to manage it and which loop should I use:
Group 1
G1_Item_1, G1_Item_2
Group 2
G2_Item_1, G2_Item_2, G2_Item_3
Upvotes: 0
Views: 46
Reputation: 350252
You could use two loops: one to restructure your data into groups, and one just for outputting it in the desired format. Note that you used <dt>
and <dd>
in the opposite sense: the groups are the titles, so use <dt>
for them.
Also, your code becomes much more readable if you don't open and close the php
tag on every line. Try to make code blocks that don't have such interruption: it will make it so more readable.
Here is the suggested code:
<?php
// Create a new structure ($groups): one entry per group, keyed by group name
// with as value the array of names:
foreach ($product['product_filters'] as $product_filter) {
$groups[$product_filter['group']][] = $product_filter['name'];
}
// Sort it by group name (the key)
ksort($groups);
// Print the new structure, using implode to comma-separate the names
foreach ($groups as $group => $names) {
echo "<dt>$group</dt><dd>" . implode(', ', $names) . "</dd>";
}
?>
See it run on eval.in.
Upvotes: 1