3

I'm trying to do recursive array in function to get all level number and the total element counts on each level for a multi-dimensional array.

I need help to achieve this goal I'm stack and can't come up of good solution.

My data

$tree = array(
        'room1' => array(
                'room5',
                'room6'
            ),
        'room2' => array(
                'room5',
                'room6'
            ),
        'room3' => array(
                'room7' => array(
                        'room12' => array(
                                'room14',
                                'room15'
                            ),
                        'room13'
                    ),
            ),
        'room4' => array(
                'room8',
                'room9',
                'room10',
                'room11'
            )
);

Desired Result

Array(
    'level1' => 4,
    'level2' => 9,
    'level3' => 2,
    'level4' => 2
)

My Code

function treeOut($tree)
{
    $markup = '';
    $count = 0;
    foreach($tree as $branch => $twig)
    {
        $count++;
        ((is_array($twig)) ? treeOut($twig,$count) : $count++;
    }
    return $count

}

echo treeOut($tree);
1

1 Answer 1

3

As 1st try

function treeOut($tree, $level=0, $counts=[])
{
  if(! isset($counts[$level])) $counts[$level] = 0; 
  foreach($tree as $branch => $twig)
    {
        $counts[$level]++;
        if(is_array($twig)) {
          $counts = treeOut($twig, $level+1, $counts);
          }
    }
    return $counts;
}

print_r(treeOut($tree));

demo

Sign up to request clarification or add additional context in comments.

2 Comments

hi @splash58! Than you! This is what Im looking for that gives me headache. Thank you very much!
@moreishi Please accept this answer since it works! Thank you splash58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.