I have a table:
| header_row | cell_usr_a | cell_usr_b | cell_fixed_a | cell_fixed_b |
| second_row |...
| usr_row_a |...
| usr_row_b |...
| usr_row_c |...
The first two columns in this example (cell_usr*) come from a dynamic object (an array of x entries); there could be 0 or many of those; the last two columns are always there.
The first two rows are always there (element name, and other general properties).
The usr_row* depend on elements in the dynamic object: if one of the element of the array has the correspondent property set, I show the row, otherwise I don’t.
How can I efficiently iterate through the object without having to re-iterate for every row?
Currently I do
foreach ($array as $element)
for every row, adding according to the size of $array.
Then I would need to first iterate through all the $element again to see if the usr_row property is set, and if yes, construct the row…
Any idea on how to do this efficiently (and possibly elegantly)?
It does not necessarily to be a table by the way.
EDIT: some more code to help illustrate my question
$packages is the object, it’s basically an array with unknown number of elements
<table>
<tr><!-- header row -->
<td>Package name</td>
<?php foreach($packages as $pkg) {
echo '<td>'.$pkg->package_name . '</td>';
} ?>
<td>fixed value</td><!-- cell_fixed_a -->
<td>no value</td><!-- cell_fixed_b -->
</tr>
<tr><!-- second row -->
<td>Count</td>
<?php foreach($packages as $pkg) {
echo '<td>'.$pkg->count . '</td>';
} ?>
<td>fixed value</td><!-- cell_fixed_a -->
<td>fixed value</td><!-- cell_fixed_b -->
</tr>
<tr><!-- usr_row_a
HERE I ONLY NEED TO HAVE THIS ROW IF any one of $pkg has prop set
-->
<?php foreach($packages as $pkg) {
if ($pkg->prop) {
echo '<tr><td>Property name</td>';
echo '<td>'. $pkg->prop . '</td>';
}
</tr>
</table>
You don’t need to loop through
$packages3 times .. you can just save the result in variablesyou can
echothem is respective places …