如何在 PHP 中以树格式返回多维数组键


How to return a multidimensional array keys in tree format in PHP?

如何在 PHP 中以树格式返回多维数组键?

例如,如果我有以下数组:

$array = array ( 
    array (
        'name' => 'A', 
        'product' => array (
            'qty' => 1,
            'brand' => 'Tim'
        ), 
        'goods' => array (
            'qty' => 2
        ), 
        'brand' => 'Lin'
    ),
    array (
        'name' => 'B', 
        'product' => array (
            'qty' => 6,
            'brand' => 'Coff'
        ),
        'goods' => array (
            'qty' => 4
        ), 
        'brand' => 'Ji'
    )
);

如何获得如下结果 - 包括不重复键:

-name
-product
--qty
--brand
-goods
--qty
--brand

递归函数应该涵盖您想要/需要的任何深度:

 function print_tree($tree, $level = 0) {
     foreach($tree AS $name => $node) {
         if(
               is_scalar($node) OR
               (
                   is_object($node) AND
                   method_exists($node, '__toString')
               )
           ) {
             echo str_repeat('-', $level).$name.': '.$node;
         }
         else if(
                   is_array($node) OR
                   (
                       is_object($node) AND
                       $node InstanceOf Traversable
                   )
                ) {
             echo str_repeat('-', $level).$name.":'n";
             print_tree($node, $level+1);
         }
     }
 }

对于无限的深度,您需要一个递归函数。我想你有父母在$names,孩子在$children:

function render_select($root=0, $level=-1) 
{
    global $names, $children;
    if ($root != 0)
       echo '<option>' . strrep(' ', $level) . $names[$root] . '</option>';
    foreach ($children[$root] as $child)
       render_select($child, $level+1);
}

此函数很有用,因为您可以为其提供 2 个变量。另一个 answas 需要一个多维数组。

function print_tree($array, $level=1) {
    foreach($array as $element) {
        if(is_array($element)) {
            print_tree($element, $level+1);
        } else {
            print str_repeat('-', $level).$element."'n";
        }
    }
}