Please provide a simple solution to the following problem in concise PHP type code (just needs to loosely follow PHP type syntax):
We want to be able to output a nested list of items – items in the list can be sub-items of other items in the list. A simple SQL table would have the following fields:
- itemID – int.
- item – varchar.
- subItemOfID – int.
A small subset of data would look something like this:
itemID item subItemOfID
1 Item1 0
2 Item2 0
3 Item3 0
4 Item10 1
5 Item11 1
6 Item12 1
7 Item100 4
8 Item101 4
9 Item102 4
10 Item30 3
11 Item31 3
12 Item32 3
The output would need to look something like this (nested lists sorted by item):
• Item1
o Item10
Item100
Item101
Item102
o Item11
o Item12
• Item2
• Item3
o Item30
o Item31
o Item32
I would get this if the SubItemOfID row was in descending order but the previous examples I used had a regex in it on the item which I was always told this was a bad way of doing something with tables because varchars can change. I need help! This is what I have so far:
<?php
$table = array (
'itemID' => array(
1,2,3,4,5,6,7,8,9,10,11,12
),
'item' => array(
'Item1','Item2','Item3','Item10','Item11','Item12','Item100','Item101','Item102','Item30','Item31','Item32'
),
'subItemOfID' => array(
0,0,0,1,1,1,4,4,4,3,3,3
)
);
foreach($table as $header => $column) {
foreach($column as $data) {
if($header == 'item') {
$fixed = intval(str_replace('Item','',$data));
$str_len = strlen($fixed);
echo '<ul>';
if($str_len === 1) {
echo '<li>'.$data.'</li>';
}
echo '<ul>';
if($str_len === 2 ) {
echo '<li>'.$data.'</li>';
}
echo'<ul>';
if($str_len ===3) {
echo '<li>'.$data.'</li>';
}
echo '</ul>';
echo '</ul>';
echo '</ul>';
}
}
}
?>
enter code here
With this query you can fetch up to 6 lvls of categories:
What does it do: selects every category and its parent categories (if exist), then generate code field to sort them.
Sorry, I inattentively read the question.
Here is the solution in php: