将嵌套的PHP分层数组展平为字符串表示形式

时间:2011-08-02 22:35:45

标签: php multidimensional-array hierarchy

给定一个数组:

0 => (
    [parent_id] => null,
    [name] => "Root"
    [children] => array(
        10 => array(
            [parent_id] => 0,
            [name] => "Category A",
            [children] => array(
                30 => array(
                    [parent_id] => 10,
                    [name] => "Category C"
                )
            )
        ),
        20 => array(
            [parent_id] => 0,
            [name] => "Category B"
        )
    )
)

我需要返回这些路径的字符串表示数组......

array(
    [0] => "Root",
    [10] => "Root > Category A",
    [30] => "Root > Category A > Category C",
    [20] => "Root > Category B"
)

我一直在乱搞这种做法,但我在做这件事时遇到了一些麻烦。有没有简单的方法可以做到这一点,我只是忽略了?

修改

解决方案只是Alexander Varwijk答案的略微修改版本。一些调整来处理不存在的子节点,通过 FUNCTION 常量递归调用函数,因此很容易更改函数名称和从array_merge更改为+运算符以组合数组以保留键

function flatten($data, $prefix = "", $item_seperator = "/") {
    $seperator = $prefix == "" ? "" : $item_seperator;
    $return = array();
    if (is_array($data)) {
        foreach($data as $key => $value) {
            $return[$value["endeca_id"]] = $prefix . $seperator . $value["url_key"];
            if(array_key_exists("children", $value))
            {
                $return = $return + call_user_func(__FUNCTION__, $value["children"], $prefix . $seperator . $value["url_key"], $item_seperator);
            }
        }
    }
    return $return;
}

2 个答案:

答案 0 :(得分:0)

我喜欢这个挑战,应该这样做:

<?php
$start = array(
    0 => array(
        'parent_id' => null,
        'name' => "Root",
        'children' => array(
            10 => array(
                'parent_id' => 0,
                'name' => "Category A",
                'children' => array(
                    30 => array(
                        'parent_id' => 10,
                        'name' => "Category C"
                    )
                )
            ),
            20 => array(
                'parent_id' => 0,
                'name' => "Category B"
            )
        )
    )
);

function recurse($data, $prefix = '') {
    $seperator = ($prefix == '' ? '' : ' > ');
    $return = array();
    if (is_array($data)) {
        foreach($data as $key => $value) {
            $return[$key] = $prefix . $seperator . $value['name'];
            $return = array_merge($return, recurse($value['children'],$prefix . $seperator . $value['name']));
        }
    }

    return $return;
}

print_r(recurse($start));
?>

答案 1 :(得分:0)

刚刚回答了上一个与此类似的5分钟问题,这可能会让您更好地了解您的行为 previous answered