I can't get it working right. What i want is that counter will count every parent and inside parent child that will look like table of content, result needs to be:
<ul>
<li><span style="color: red;">1</span> <strong>a</strong>
</li>
<ul>
<li><span style="color: red;">1.1</span> <strong>b</strong>
</li>
<li><span style="color: red;">1.2</span> <strong>c</strong>
</li>
</ul>
<li><span style="color: red;">2</span> <strong>e</strong>
</li>
<ul>
<li><span style="color: red;">2.1</span> <strong>f</strong>
</li>
<li><span style="color: red;">2.2</span> <strong>g</strong>
</li>
</ul>
<li><span style="color: red;">3</span> <strong>h</strong>
</li>
<ul>
<li><span style="color: red;">3.1</span> <strong>k</strong>
</li>
<li><span style="color: red;">3.2</span> <strong>l</strong>
</li>
<ul>
<li><span style="color: red;">3.2.1</span> <strong>m</strong>
</li>
<li><span style="color: red;">3.2.2</span> <strong>n</strong>
</li>
</ul>
</ul>
</ul>
There are n childs soo deep is unlimited.. My current code is here:
<?php
$arr = array(
array('id' => 1, 'title' => 'a', 'parent' => 0),
array('id' => 2, 'title' => 'b', 'parent' => 1),
array('id' => 3, 'title' => 'c', 'parent' => 1),
array('id' => 5, 'title' => 'e', 'parent' => 0),
array('id' => 6, 'title' => 'f', 'parent' => 5),
array('id' => 7, 'title' => 'g', 'parent' => 5),
array('id' => 8, 'title' => 'h', 'parent' => 0),
array('id' => 9, 'title' => 'k', 'parent' => 8),
array('id' => 10, 'title' => 'l', 'parent' => 8),
array('id' => 11, 'title' => 'm', 'parent' => 10),
array('id' => 12, 'title' => 'n', 'parent' => 10),
);
function checkChilds($arr, $id){
foreach ($arr as $key => $value) {
if ($value['parent'] == $id) {
return true;
}
}
return false;
}
function getList($arr, $parent = 0, $subcounter = 1){
$output = null;
$output .= '<ul>';
$counterParent = 1;
$countChild = 1;
foreach($arr as $key => $value) {
if($value['parent'] == $parent){
$counter = ($value['parent'] == 0) ? "{$counterParent}" : "{$subcounter}.{$countChild}";
$output .= "<li><span style='color: red;'>{$counter}</span> <strong>{$value['title']}</strong></li>";
if (checkChilds($arr, $value['id'])){
$output .= getList($arr, $value['id'], $counterParent);
$countChild++;
}
// counter for parent
if($value['parent'] == 0) {
$counterParent++;
}
}
}
$output .= '</ul>';
return $output;
}
echo getList($arr);
</div>