【问题标题】:How to count array level "deep" number and count total elements on each level of an array in PHP如何在PHP中计算数组级别“深”数并计算数组每个级别上的总元素
【发布时间】:2018-07-09 14:54:44
【问题描述】:

我正在尝试在函数中执行递归数组以获取多维数组的所有级别编号和每个级别的总元素计数。

我需要帮助来实现这个目标我是堆栈,无法想出好的解决方案。

我的数据

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

想要的结果

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

我的代码

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

}

echo treeOut($tree);

【问题讨论】:

标签: php arrays recursion multidimensional-array


【解决方案1】:

第一次尝试

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

【讨论】:

  • 嗨@splash58!比你!这就是我正在寻找的让我头疼的东西。非常感谢!
  • @moreishi 请接受这个答案,因为它有效!谢谢splash58
猜你喜欢
  • 2018-01-08
  • 2018-03-13
  • 1970-01-01
  • 2017-07-15
  • 1970-01-01
  • 1970-01-01
  • 2020-09-17
  • 2021-05-14
  • 2022-08-05
相关资源
最近更新 更多