I'm struggling to verbalise this question, but hopefully I can demonstrate it:
I wish for certain results in a foreach loop to be grouped together in a container in the front-end.
So, if, for example, I have a foreach loop running through an array of car names and colours:
foreach($cars as $car){
echo '<h1>'.$car->name.'</h1>';
echo '<p>'.$car->colour.'</p><br/>';
}
It may give me:
<h1>Car1</h1>
<p>Blue</p><br/>
<h1>Car2</h1>
<p>Blue</p><br/>
<h1>Car3</h1>
<p>Red</p><br/>
However I need to group results with the same colour into a container div, so the output looks like:
<div class="blue">
<h1>Car1</h1>
<p>Blue</p><br/>
<h1>Car2</h1>
<p>Blue</p><br/>
</div>
<h1>Car3</h1>
<p>Red</p><br/>
Because the container div is technically outside of each loop I'm not sure how I can get it in there without using front-end script (i.e. javascript), but I'm hoping there's a way… any ideas? Perhaps even a way to identify the first of a type and the last of a type - but that's the closest I can get to a theory, let a lone a solution.
Edit: It appears there was some misunderstanding over the question. I wasn't looking to programatically group within the foreach, simply 'wrap' pre-grouped items.
Use a multi-dimensional array to build your data structure, then loop through the array to display your output.
Something like this:
$mycars = array();
foreach($cars as $car){
$mycars[$car->colour][] = $car;
}
Now you have an array that looks like this:
Array
(
[Blue] => Array
(
[0] => {Car1Object}
[1] => {Car2Object}
)
[Red] => Array
(
[0] => {Car3Object}
)
)
Now loop through that array to display your output:
foreach($mycars as $colour => $cars) {
echo "<div class='$colour'>";
foreach($cars as $car) {
echo "<h1>{$car->name}</h1>";
echo "<p>{$car->colour}</p>";
}
echo "</div>";
}
And you get...
<div class='Blue'>
<h1>Car1</h1>
<p>Blue</p>
<h1>Car2</h1>
<p>Blue</p>
</div>
<div class='Red'>
<h1>Car3</h1>
<p>Red</p>
</div>