I've got a function I've been working on that will recursively get all the content from either my pages or categories table. I normalized the names across both tables that the function calls: id, title, and parentID. It gets the information correctly when I call it either way, but the only problem I have now is when I call it, it seems to jumble the order of the array around? I'm not sure...
function displayTree($parentID, $level, $tableName) {
$tableName = strtolower($tableName);
$sql = 'SELECT `id`,`title`,`parentID` FROM ';
if ($tableName == 'categories') {
$sql .= 'categories WHERE parentID="'.$parentID.'";';
}
else {
$sql .= 'pages WHERE parentID="'.$parentID.'";';
}
$result = mysql_query($sql);
if (!$result) {
echo 'There was an error executing your query.';
mysqlLog(mysql_error());
$tree = array();
}
else {
$tree = array();
while ($row = mysql_fetch_array($result)) {
$tree[] = array('id' => $row['id'], 'title' => str_repeat(' -- ',$level).$row['title']);
$tree = array_merge(displayTree($row['id'], $level+1, $tableName), $tree);
}
}
return $tree;
}
That's the function code. Here's the snippet I'm calling and displaying it with:
echo '<table name="pageDisplay" width="100%" cellpadding="2px" cellspacing="2px" border="0">
<tr bgcolor="#BBBBBB"><td>ID</td><td>Title</td><td colspan="3" style="text-align: center;">Actions</td></tr>';
$pagesTree = displayTree('', 0, 'pages');
$rowColors = array(0 => '#FFFFFF', 1 => '#CCCCCC');
$rowCount = 1;
for ($i = 0; $i < sizeof($pagesTree); $i++) {
$rowCount = 1 - $rowCount;
echo '<tr style="background: '.$rowColors[$rowCount].'"><td>'.$pagesTree[$i]['id'].'</td><td>'.$pagesTree[$i]['title'].'</td><td>View</td><td>Edit</td><td>Delete</td></tr>';
}
echo '</table>';
And here is how it outputs:
ID Title Actions
5 -- Test... again! View Edit Delete
4 -- -- Page 4, sub 2 View Edit Delete
6 -- -- asdf View Edit Delete
3 -- Page 3, sub 1 View Edit Delete
1 First HorizonSM test page View Edit Delete
2 Second Test Page View Edit Delete
Which isn't quite right, because it should show ID 1, then the sub-pages of 1, then ID 2, it's subpages, so on and so forth. Any recommendations/ideas?