moreishi
moreishi

Reputation: 63

How to count array level "deep" number and count total elements on each level of an array in PHP

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);

Upvotes: 3

Views: 2370

Answers (1)

splash58
splash58

Reputation: 26153

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

Upvotes: 3

Related Questions