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



给定一个数组:

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"
)

我一直在用递归的方式做这个,但是我在高效地做这个时有一些麻烦。有没有我忽略了的简单方法?

编辑:

Solution只是Alexander Varwijk的答案的一个稍微修改的版本。一些调整来处理不存在的子函数,通过 function constant递归调用函数,这样可以很容易地更改函数名,并将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;
}

我喜欢这个挑战,这个应该可以做到:

<?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));
?>

相关内容

  • 没有找到相关文章

最新更新