(Before anyone asks... I cannot use a MySQL database for this project.)
Using PHP, I need to create nested UL's from a flatfile database. The issue that I'm having is that I don't want duplicate items displayed. I could explain further, but if you'll take a look at the code below, you'll see the data and the goal. Thanks.
FLATFILE DATA:
section|category|service Section One|Category One| Section One|Category Two|SC1 Section One|Category Two|SC2 Section One|Category Two|SC3 Section One|Category Two|SC4 Section One|Category Three| Section Two|Category Four|SC5 Section Two|Category Four|SC6 Section Three|Category Five|SC7
HTML GOAL OUTPUT:
<ul class="section">
<li>Section One
<ul class="category">
<li>Category One</li>
<!-- no service -->
</ul> <!-- /category -->
<ul class="category">
<li>Category Two</li>
<ul class="service">
<li>SC1</li>
<li>SC2</li>
<li>SC3</li>
<li>SC4</li>
</ul> <!-- /service -->
</li>
</ul> <!-- /category -->
<ul class="category">
<li>Category Three</li>
<!-- no service -->
</ul> <!-- /category -->
</li>
</ul> <!-- /section -->
<ul class="section">
<li>Section Two
<ul class="category">
<li>Category Four</li>
<ul class="service">
<li>SC5</li>
<li>SC6</li>
</ul> <!-- /service -->
</li>
</ul> <!-- /category -->
</li>
</ul> <!-- /section -->
<ul class="section">
<li>Section Three
<ul class="category">
<li>Category Five</li>
<ul class="service">
<li>SC7</li>
</ul> <!-- /service -->
</li>
</ul> <!-- /category -->
</li>
</ul> <!-- /section -->
My 1st attempt... thinking that I need to first check if the "section" exists, then assign the current "section" to a "section_last" to compare the next "section" with the current "section" value ... and if not, print the "section" ... and then onto the category. I didn't code the "service" value section because I wasn't haven't any success with the section & category values. It seems that I'm having an issue with either the 'logic' behind this or maybe there's a method for comparing the past value in the loop with the next value that PHP offers that I'm missing.
After seeing the example code from @Kyle S, I may be on a completely incorrect path for coding this.
<?php
$section = '';
$category = '';
$service = '';
$section_last = '';
$category_last = '';
$service_last = '';
$x = 0;
$file = fopen("categories_data.txt", "r");
if (!$file) { echo 'ERROR: Unable to open file: <strong>'.$file.'</strong>'; }
fgets($file); // IGNORE FIRST LINE IN FLATFILE - column names
while (!feof($file) ) {
$lines = fgets($file);
$ele = explode('|', $lines);
$section = $ele[0];
$category = $ele[1];
$service = $ele[2];
$service = str_replace(array("\n", "\r", "\r\n", "\n\r"), '',$service);
if(strlen($section)>0) {
if(!($section == $section_last)) {
echo '
<ul>
<li>'.$section;
$section_last = $section;
$x++;
}
}
echo '
<ul><li>'.$category.' > '.$service.'</li></ul>
';
if($x) {
if($section != $section_last) {
echo '
</li>
</ul>
';
}
}
} // end $data_file WHILE
fclose($file);
?>