一个二维数组,如何循环遍历将第一个数组作为下一级数组的父级,然后生成一个树型结构

<?php
$a = [['a'],['b'],['c'],['d'],['e']];
function getTree($list) {
    static $tree = array();
    static $i=0;
    $i++;
    $len = count($list);
    foreach($list as $k => $row) {
        if($i+$k == $len) {
            $tmp[] = $row[0];
            $tmp['child'] = isset($tree[count($tree)-1])?$tree[count($tree)-1]:$tree;
            $tree[] = $tmp;
            getTree($list);
        }
    }
    return end($tree);
}
$c  = getTree($a);
var_export($c);

结果

array (
  0 => 'a',
  'child' => 
  array (
    0 => 'b',
    'child' => 
    array (
      0 => 'c',
      'child' => 
      array (
        0 => 'd',
        'child' => 
        array (
          0 => 'e',
          'child' => 
          array (
          ),
        ),
      ),
    ),
  ),
)

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注