I am trying to have the function print the # of sub items in each parent item but can't seem to get that to work. For some reason print_r(count($arr[$key]['children'])) is outputting first, then looping through the rest and putting a number 1 where it is supposed to be returning a count.
function create_list($arr)
{
$html = "";
foreach($arr as $key => $value) {
if(count($value['children']) > 0) {
$html .= $value['name'].' (' . print_r(count($arr[$key]['children'])) . ')<ul>';
foreach($value['children'] AS $child) {
$html .= ' <li><a id="'.$child['menu_item_id'].'">'.$child['name'].'</a></li>';
}
$html .= ' </ul>
';
} else{
$html .= ' <a class="menuitem" id="'.$value['menu_item_id'].'">'.$value['name'].'</a>';
}
}
return $html;
}
echo create_list($menu_items);
Outputs the following:
22Main Task (1)
o second task
o sub task
George (1)
o test
o tester
Where it says 22MainTask, the 22 is the results from the count from each root level item. What is the proper way to return a count on that? I am hoping to be able to also print (2/5) tasks complete type, but if I could at least get it to return an accurate count that would be a great first step.
print_r? why not justcount($arr[$key]['children'])? you are already concatenating this within a string soprint_ris redundant. Also,print_r(as well asvar_dump) output straight to the browser, i.e. bypasses html rendering, so that would be why22appears before your htmlhtmlspecialchars()around arbitrary data used in the context of HTML. At best, you're creating invalid HTML once in awhile, and at worse you are open to XSS attacks.