Alan
Alan

Reputation: 2086

PHP Function Output Screwy

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.

Upvotes: 0

Views: 37

Answers (1)

pythonjsgeo
pythonjsgeo

Reputation: 5411

Add a second parameter to return the value instead of printing it immediately.

print_r($data, true)

In your example, it prints a count of "1" because print_r returns true (which is converted to "1") if you don't provide the second parameter as true.

Upvotes: 1

Related Questions