PHP递归 - 在一个级别上显示子数组

时间:2016-05-02 15:30:19

标签: php arrays recursion

我有以下数组:

$example = array(
array(
    'id' => 63,
    'parentid' => 0,
    'char_value' => 'End poverty in all its forms everywhere',
    'param_value' => 1,
    'children' => array(
        array(
            'id' => 84,
            'parentid' => 63,
            'char_value' => 'test 1',
            'param_value' => 1
        ),
        array(
            'id' => 85,
            'parentid' => 63,
            'char_value' => 'test 2',
            'param_value' => 1
        )
    )
));

以下函数用于递归:

function drawPropertyTree($array, $parent){
$result = array();
foreach ($array as $k => $v) {

    $pieces = explode(" ", $v['char_value'], 6);
    $name   = implode(" ", array_splice($pieces, 0, 3));

    $result[] = array(
        'id' => $v['id'],
        'parent' => $parent,
        'text' => $v['param_value'] . " " . $name
    );

    if (isset($v['children'])) {
        $result[] = drawPropertyTree($v['children'], $v['id']);
    }
}
return $result;}

我想列出与父节点在同一级别上的所有子阵列。这是working sample,这是当前的输出:

Array
(
[0] => Array
    (
        [id] => 63
        [parent] => 0
        [text] => 1 End poverty in
    )

[1] => Array
    (
        [0] => Array
            (
                [id] => 84
                [parent] => 63
                [text] => 1 test 1
            )

        [1] => Array
            (
                [id] => 85
                [parent] => 63
                [text] => 1 test 2
            )

    )
)

这是理想的结果:

Array (
[0] => Array
    (
        [id] => 63
        [parent] => 0
        [text] => 1 End poverty in
    )
[1] => Array
        (
            [id] => 84
            [parent] => 63
            [text] => 1 test 1
        )

[2] => Array
        (
            [id] => 85
            [parent] => 63
            [text] => 1 test 2
        )

2 个答案:

答案 0 :(得分:1)

您需要的功能稍有变化 - 假设您需要支持任意深度:

function drawPropertyTree($array, $parent)
{
    $result = array();
    foreach ($array as $k => $v) {

        $pieces = explode(" ", $v['char_value'], 6);
        $name   = implode(" ", array_splice($pieces, 0, 3));

        $result[] = array(
            'id'     => $v['id'],
            'parent' => $parent,
            'text'   => $v['param_value'] . " " . $name
        );

        if (isset($v['children'])) {
            // drawPropertyTree returns an array
            // which must be merged into the existing array
            $result = array_merge($result, drawPropertyTree($v['children'], $v['id']));
        }
    }
    return $result;
}

答案 1 :(得分:0)

创建新的空数组并将所有元素推入for循环,并检查子节点以将它们推送到新数组中。没有任何递归