如何返回树格式多维数组键PHP? [英] How to return a multidimensional array keys in tree format in PHP?

查看:150
本文介绍了如何返回树格式多维数组键PHP?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能返回树格式多维数组键PHP?

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

  $阵列=阵列(
    阵列(
        '名'=> '一个',
        '产品'= GT;阵列(
            '数量'=> 1,
            '品牌'=> 蒂姆
        )
        '品'=>阵列(
            '数量'=> 2
        )
        '品牌'=> '林'
    )
    阵列(
        '名'=> B,
        '产品'= GT;阵列(
            '数量'=> 6,
            '品牌'=> COFF
        )
        '品'=>阵列(
            '数量'=> 4
        )
        '品牌'=> 吉
    )
);

我怎样才能得到一个结果类似如下 - 包括没有重复键的:

  -name
-产品
--qty
- 牌
-产品
--qty
- 牌


解决方案

具有无限的深度需要一个递归函数。我想你在$名家长和孩子的在$儿童:

 函数render_select($根= 0,$水平= -1)
{
    全球$名称,$儿童;
    如果($根!= 0)
       呼应'<选项>' 。 strrep('',$级)。 $名称[$根。 '< /选项>';
    的foreach($儿[$根]为$子)
       render_select($孩子,$级+ 1);
}

这个功能很有用用,因为你可以用两个变量来滋润它。其他的answere需要一个多维数组。

How can I return multidimensional array keys in tree format in PHP?

For example, if I have the following array:

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

How can I get a result like the following -- including no repeating of keys:

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

解决方案

With an unlimited depth you need a recursive function. I suppose you have the parents in $names and the childs in $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);
}

This functions use useful because you can feed it with 2 variables. The other answere requires a multidimensional array.

这篇关于如何返回树格式多维数组键PHP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆