How to do this type of incrementation in PHP?
I am using this category script:
<?php
include("connect.php");
$nav_query = mysql_query("SELECT * FROM `categories` ORDER BY `id`");
$tree = "";
$depth = 1;
$top_level_on = 1;
$exclude = array();
array_push($exclude, 0);
while ($nav_row = mysql_fetch_array($nav_query)) {
$goOn = 1;
for ($x = 0; $x < count($exclude); $x++) {
if ($exclude[$x] == $nav_row['id']) {
$goOn = 0;
break;
}
}
if ($goOn == 1) {
$tree .= $nav_row['name'] . "<br>";
array_push($exclude, $nav_row['id']);
if ($nav_row['id'] < 6) {
$top_开发者_如何学编程level_on = $nav_row['id'];
}
$tree .= build_child($nav_row['id']);
}
}
function build_child($oldID) {
global $exclude, $depth;
$child_query = mysql_query("SELECT * FROM `categories` WHERE parent_id=" . $oldID);
while ($child = mysql_fetch_array($child_query)) {
if ($child['id'] != $child['parent_id']) {
for ($c=0; $c < $depth; $c++) {
$tempTree .= " ";
}
$tempTree .= "- " . $child['name'] . "<br>";
$depth++;
$tempTree .= build_child($child['id']);
$depth--;
array_push($exclude, $child['id']);
}
}
return $tempTree;
}
echo $tree;
?>
It relies on the following mysql database structure:
id | parent_id | name
1 Cats
2 1 Siamese Cats
3 2 Lilac Point Siamese Cats
4 Dogs
etc...
The script allows for unlimited category depth but has one major downfall. It displays the category navigation to the front end like so:
Cats
- Siamese Cats
- Lilac Point Siamese Cats
Dogs
How can I have it display like this:
Cats
- Siamese Cats
- Lilac Point Siamese Cats
Dogs
So that for each additional category depth another space with be added to the beginning indentation of the category text?
As you are already keep track of the depth, make use of it. E.g.
$indent = '';
for($i = 0; $i < $depth; $i++) {
$indent .= " ";
}
$tempTree .= $indent . "- " . $child['name'] . "<br>";
To make it look the way you want it you might have to initialize $depth
with 0
.
Also note that executing SQL queries in a nested for
loop is not the best approach. If possible, try to reduce the number of queries.
You could for example use classes and, get all the entries at once and then build the tree structure with objects and arrays.
精彩评论