Reputation:
i have two db tables in my codeigniter project. As simplified summary,
page page_lang
------------------------------------- ----------------------------
id_page | id_menu | id_parent | level id_page | title | etc..
------------------------------------- ----------------------------
1 | 1 | 0 | 0 1 | Name 1 | etc..
2 | 1 | 1 | 1 2 | Name 1.1 | etc..
3 | 1 | 2 | 2 3 | Name 1.1.1 | etc..
4 | 1 | 2 | 1 4 | Name 1.2 | etc.
I am trying to create a dropdown select box which contains all page nested with indents as output like;
<option value="id_page">Name 1</option>
<option value="id_page"> » Name 1.1</option>
<option value="id_page"> - Name 1.1.1</option>
<option value="id_page"> » Name 1.2</option>
In this case, in need join page and page_lang and create a recursive loop, i quess.
But I am stacked on designing the fastest possible code. Thank you for any help.
Upvotes: 1
Views: 890
Reputation: 1777
Your recursive function will look something like this
function recursivePageOptions( $level, $nodes ) {
$set = array();
foreach ($nodes as $node) {
$nest = '';
for($x=1; $x<=$level; $x++)
$nest.= ' ';
$page = '<option value="'.$node['page']['id'].'">';
$page.= $nest . $node['page']['title'] . '</option>';
$set[] = $page;
if (isset($node['children'])) {
$set = array_merge(
$set,
recursivePageOptions( $level+1, $node['children'] );
);
}
}
return $set;
}
So what you need to do before this recursive function is called is get your page information into an array structure that looks like this:
[
'My Homepage' => [
'page' => ['My Homepage', 24, ... ],
'children' => [
'Level 1 Page' => [
'page' => ['Level 1 Page', 39, ... ],
'children' => [
'Level 2 Page' => [
'page' = ['Level 2 Page', 51, ... ]
]
]
],
'Another Level 1 Page' =< [
'page' => ['Another Level 1 Page', 56, ... ]
]
]
]
]
Its up to you to figure this part out in detail, essentially you will be getting rows out of the database and looping through them in such a way as to generate an array structure like the one above.
Upvotes: 2