PHP:遍历数组?

Ind*_*ial 1 php arrays recursion multidimensional-array

  • 我想要一个函数来搜索我的数组,并将所有子节点返回到特定节点。最合适的方法是什么?在这种情况下需要递归吗?

我之前构建了一些相当复杂的函数,这些函数在有或没有递归的帮助下通过多维数组进行迭代并重新排列它们,但是这个问题让我完全陷入困境,我不能只是解决它......

这是我的数组:

Array
(
    [1] => Array (
            [id] => 1
            [parent] => 0

        )

    [2] => Array (
            [id] => 2
            [parent] => 1
        )

    [3] => Array (
            [id] => 3
            [parent] => 2
        )
)
Run Code Online (Sandbox Code Playgroud)

更新:

我想要得到的输出。抱歉这个不好的例子,但我会把它归咎于缺乏如何格式化我需要做的事情的知识:)

function getAllChildren($id) {
    // Psuedocode
    return $array;
}

getAllChildren(1); // Outputs the following:

Array
(
    [2] => Array (
            [id] => 2
            [parent] => 1
        )

    [3] => Array (
            [id] => 3
            [parent] => 2
        )
)
Run Code Online (Sandbox Code Playgroud)

Mar*_*ker 5

$nodes = array( 1   => array (  'id'        => 1,
                                'parent'    => 0
                             ),
                2   => array ( 'id'         => 2,
                               'parent'     => 1
                             ),
                3   => array ( 'id'         => 3,
                               'parent'     => 2
                             )
                );


function searchItem($needle,$haystack) {
    $nodes = array();
    foreach ($haystack as $key => $item) {
        if ($item['parent'] == $needle) {
            $nodes[$key] = $item;
            $nodes = $nodes + searchItem($item['id'],$haystack);
        }
    }
    return $nodes;
}


$result = searchItem('1',$nodes);
echo '<pre>';
var_dump($result);
echo '</pre>';
Run Code Online (Sandbox Code Playgroud)

searchItem() 函数的非递归版本:

function searchItem($needle,$haystack) {
    $nodes = array();
    foreach ($haystack as $key => $item) {
        if (($item['parent'] == $needle) || array_key_exists($item['parent'],$nodes)) {
            $nodes[$key] = $item;
        }
    }
    return $nodes;
}
Run Code Online (Sandbox Code Playgroud)

(假设父节点/子节点的顺序,因此子节点不会包含在数组中,除非父节点已经存在)