I'm writing some PHP to generate a table of contents. The idea is for me to write the minimum code each time I make a TOC.
So normally, a single entry might look like this:
- Code: Select all
<li><a href=\"".$host."/articles/serving-guide/badminton-serve-types.php\">The four types of serve</a></li>
Instead, I want PHP to
create this code from (part of) a variable like this:
- Code: Select all
$tocList = "||badminton-serve-types|The four types of badminton serve";
Here, I use the "||" to separate items and the "|" to separate the URL from the anchor text.
With me so far? That bit is okay, but I also need to nest lists to create subsections (one level of nesting). I do this by adding the signal characters "+" and "-" onto the end of the title. "+" signals "opening a nested list" and "-" signals "closing a nested list".
This part -- the nested lists -- is causing problems with my foreach loop. It only applies the test for the
last entry; all other signalled entries are being ignored by the loop.
Here's my full code:
- Code: Select all
<?php
$tocArray =
"|Introduction
||basic-technique/|Basic serving technique+
||backhand-low-serve-technique|Backhand low serve
||backhand-flick-serve-technique|Backhand flick serve-
||tactics|Serving tactics";
$tocList=explode("||", $tocArray);
$directory = ""; // placeholder empty string;
foreach($tocList as $value) {
$temp = explode("|",$value);
$temp3 = trim($temp[1]); $temp4 = rtrim($temp3, "+-"); // removes nesting-signal characters from anchor text
if ( (substr($temp[0], -1) != "/") && ( strlen($temp[0]) > 0) ) {$temp[0] .= ".php";} // adds .php for all non-directory URLs
$tocURL = $host."/articles/".$article."/".$directory.$temp[0]; // creates a URL
if ($tocURL == ($host.$path)) { $entry ="<li class=\"here\"><span>".$temp4."</span>"; } // "you are here" formatting
else { $entry = "<li><a href=\"".$tocURL."\">".$temp4."</a>"; } // normal link
$temp2 = substr($temp[1], -1);
if ($temp2 == "+") { // for the start of a section
$directory = $temp[0]; // capturing the directory string for later
echo $entry."<ol>\n\t"; // starting a nested list
echo "DEBUG: I dont understand PHP";
}
if ($temp2 == "-") { // for the end of a section
echo $entry."</li>\n\t</ol></li>"; // ending nested list
$directory = ""; // resetting directory
}
if ($temp2 != "-" && $temp2 != "+") { echo $entry."</li>\n"; }
}
?>
The only way to activate my debug text is by changing the
last item to have a signal "+", like this:
- Code: Select all
$tocArray =
"|Introduction
||basic-technique/|Basic serving technique+
||backhand-low-serve-technique|Backhand low serve
||backhand-flick-serve-technique|Backhand flick serve-
||tactics|Serving tactics+";
If I do this, then
if ($temp2 == "+") evaluates as true, and the debug text appears.
What's going on?