vendredi 27 mars 2015

Loop through a two-dimensional array with actions on change of a value in a column

A very common problem while looping throug a two-dimensional array (representing a table) is to have an action to execute only when a value in a column changes. To give a concrete example:


Output some HTML from tabular data.

Given this table



category | product
------------------
Vehicles | Bike
Vehicles | Car
Clothes | Shirt


Create HTML like this:



<h1>Vehicles</h1>Bike<br />Car<hr />
<h1>Clothes</h1>Shirt<hr />


To solve the problem, I could change the code like this:



$current_category = '';
$first = true;
foreach($table as $row){
if ($row['category'] != $current_category){
if(!$first){
// after a group
$echo '<hr />';
}
// before a group
echo '<h1>'.$row['category'].'</h1>';
} else if (!$first){
// inside a group
echo '<br />';
}
// foreach line
echo $row['category'];
$current_category = $row['category'];
$first = false;
}
// after a group, duplicated code
$echo '<hr />';


I feel that this is more complicated than necessary. Also there is code duplication for what I want to execute after the group.


The code for this relatively simple requirement is already convoluted. It get's almost impossible, if we need to watch two changing columns in the array.


I'm looking for an approach of this problem that keeps the code easy to read, while being able to loop through the array and execute some code



  • foreach line

  • before a group of lines

  • after a group of lines

  • inside a group of lines


I hope the question is clear, even though I have some difficulty to explain this general problem in simple terms.


Aucun commentaire:

Enregistrer un commentaire